Python - 将日期数字转换为特定年份的日期
给定天数,转换为它所指的日期。
Input : day_num = “339”, year = “2020”
Output : 12-04-2020
Explanation : 339th Day of 2020 is 4th December.
Input : day_num = “4”, year = “2020”
Output : 01-04-2020
Explanation : 4th Day of 2020 is 4th January.
方法 #1:使用 datetime.strptime()
在此,我们获取年份字符串和日期数字字符串,并传递给 strptime(),转换为相应的所需日期。
Python3
# Python3 code to demonstrate working of
# Convert day number to date in particular year
# Using datetime.strptime()
from datetime import datetime
# initializing day number
day_num = "339"
# print day number
print("The day number : " + str(day_num))
# adjusting day num
day_num.rjust(3 + len(day_num), '0')
# Initialize year
year = "2020"
# converting to date
res = datetime.strptime(year + "-" + day_num, "%Y-%j").strftime("%m-%d-%Y")
# printing result
print("Resolved date : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert day number to date in particular year
# Using datetime.strptime()
from datetime import datetime, date, timedelta
# initializing day number
day_num = "339"
# print day number
print("The day number : " + str(day_num))
# adjusting day num
day_num.rjust(3 + len(day_num), '0')
# Initialize year
year = "2020"
# Initializing start date
strt_date = date(int(year), 1, 1)
# converting to date
res_date = strt_date + timedelta(days=int(day_num) - 1)
res = res_date.strftime("%m-%d-%Y")
# printing result
print("Resolved date : " + str(res))
输出
The day number : 339
Resolved date : 12-04-2020
方法#2:使用timedelta()
在这里,我们将日期初始化为 1 月 1 日,然后使用 timedelta() 添加天数,结果给出了所需的日期。
蟒蛇3
# Python3 code to demonstrate working of
# Convert day number to date in particular year
# Using datetime.strptime()
from datetime import datetime, date, timedelta
# initializing day number
day_num = "339"
# print day number
print("The day number : " + str(day_num))
# adjusting day num
day_num.rjust(3 + len(day_num), '0')
# Initialize year
year = "2020"
# Initializing start date
strt_date = date(int(year), 1, 1)
# converting to date
res_date = strt_date + timedelta(days=int(day_num) - 1)
res = res_date.strftime("%m-%d-%Y")
# printing result
print("Resolved date : " + str(res))
输出
The day number : 339
Resolved date : 12-04-2020