📜  Python - 将日期数字转换为特定年份的日期

📅  最后修改于: 2022-05-13 01:54:42.025000             🧑  作者: Mango

Python - 将日期数字转换为特定年份的日期

给定天数,转换为它所指的日期。

方法 #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