以下代码的目的是将日期转换为相应的日期。我把2017年10月2日作为参考,然后继续进行。我不完全理解deltatime并猜测问题可能与我如何使用它有关。希望有人能帮助我。
import datetime
ans = 'Y'
today = datetime.date(2017, 10, 2)
while ans is 'Y' or ans is 'y':
d = input("Enter a date (DD/MM/YYYY)")
day = int(d[:2])
month = int(d[3:5])
year = int(d[6:])
thatday = datetime.date(year, month, day)
deltat = thatday - today
dif = int(deltat.days/7)
if dif is 6:
print("Sunday")
elif dif is 1:
print("Tuesday")
elif dif is 2:
print ("Wednesday")
elif dif is 3:
print("Thursday")
elif dif is 4:
print("Friday")
elif dif is 5:
print("Saturday")
else:
print("Monday")
ans = input("One more time, eh? (y/n)")
答案 0 :(得分:0)
我开始尝试帮助你,但当我没有真正明白你的需要时迷路了。
基本上我认为您需要阅读strftime,它以特定方式打印日期时间对象:例如datetime.strftime("%A")给出工作日。你还需要strptime从字符串中读取日期,例如datetime.strptime(&#34 31 /一千九百九十九分之十二""%d /%米/%Y&#34)
请查看以下修改后的代码:
import datetime
ans = 'Y'
today = datetime.datetime.now().date()
while ans.title() == 'Y':
d = input("Enter a date (DD/MM/YYYY)")
thatday = datetime.datetime.strptime(d,"%d/%m/%Y").date()
deltat = thatday - today # timedelta
dif = int(deltat.days/7) # timedelta/7? What is this?
print(thatday.strftime("%A")) # Here you get the weekday of thatday
ans = input("One more time, eh? (y/n)")
答案 1 :(得分:0)
如果您只是在寻找一周中的某一天,您也可以这样做。 weekday()返回一个整数值,其中Monday为0,Sunday为6
from datetime import *
weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
d = date(2017, 10, 2).weekday()
print(weekdays[d])
该日期返回星期一