[英]How to get relevant month and date by inputting only the day of year in python
I'm developing a phonebook application from python as a mini project in which I'm having the requirement to store the NIC number of a person and then display his/her gender, DOB and age. 我正在开发python的电话簿应用程序作为一个迷你项目,我需要存储一个人的NIC号码,然后显示他/她的性别,DOB和年龄。 I have to derive these 3 information and I'm able to derive the gender, but I don't know how to derive the DOB - only the birth year because the NIC number's first 2 digits represent the year of birth. 我必须得出这3个信息并且我能够得出性别,但我不知道如何得出DOB - 只有出生年份,因为NIC号码的前2位代表出生年份。
In a NIC number, the 3rd three digits are the day of year :- from 001 to 366. I can seperate those 3 digits to another variable as well, but how do I derive the month and the date of month which it refers to? 在一个NIC编号中,第三个三位数是一年中的某一天: - 从001到366.我也可以将这3个数字分隔给另一个变量,但我如何得出它所指的月份和月份日期?
For example : 例如 :
derivedYear = 1996
dayOfYear = 032
finalDOB = "1996.02.01"
print finalDOB
I want to know how to calculate the finalDOB value. 我想知道如何计算finalDOB值。 I'm using python 2.7.6 我正在使用python 2.7.6
You can use timedelta()
. 你可以使用timedelta()
。 It can take days as an argument, and when added to a date, will shift it by that amount. 它可能需要数天才能作为参数,并且当添加到日期时,会将其移动该数量。
import datetime
year = 1996
days = 32
date = datetime.date(year, 1, 1) #Will give 1996-01-01
delta = datetime.timedelta(days - 1) #str(delta) will be '31 days, 0:00:00'
newdate = date + delta
>>> str(newdate)
>>> 1996-02-01
or 要么
>>> newdate.strftime('%Y.%m.%d')
>>> '1996.02.01'
You can use %j
format for day of year in datetime.datetime.strptime()
, to get the corresponding datetime object . 您可以在datetime.datetime.strptime()
使用%j
格式表示datetime.datetime.strptime()
,以获取相应的日期时间对象。 Example - 示例 -
>>> derivedYear = 1996
>>> dayOfYear = 32
>>> import datetime
>>> d = datetime.datetime.strptime('{} {}'.format(dayOfYear, derivedYear),'%j %Y')
>>> d
datetime.datetime(1996, 2, 1, 0, 0)
Then you can use the .day
and .month
attribute of the datetime object to get the corresponding day and month. 然后,您可以使用datetime对象的.day
和.month
属性来获取相应的日期和月份。 Example - 示例 -
>>> d.day
1
>>> d.month
2
If you want the result in format - YYYY.MM.DD
- you can use strftime()
and supply the format to it. 如果你想要格式的结果YYYY.MM.DD
- 你可以使用strftime()
并为它提供格式。 Example - 示例 -
>>> d.strftime('%Y.%m.%d')
'1996.02.01'
Also, please note, you should not define your dayOfYear
with a leading 0
, as that would make the literal an octal number, which would not be what you want. 此外,请注意,您不应该使用前导0
定义dayOfYear
,因为这会使文字成为八进制数,这不是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.