我对datetime对象有问题。这是我的密码:
import datetime
import pytz
userInfo = 'Europe/Istanbul'
# Current date, 2020-9-8 15:00
cd = datetime.datetime.now(pytz.timezone(userInfo))
# Example date, 2020-9-8 15:00
ed = datetime.datetime(2020, 9, 8, 15, 0, pytz.timezone(userInfo))
# Print both dates
print('Example', ed, '\n', 'Current', cd, '\n')
if ed == cd:
print('Equal')
else:
print('Not worked')正如您所看到的,这些日期是相等的,但是当我试图打印它们时,它给出了以下结果:
Example 2020-9-8 15:00:00.000000+01:56
Current 2020-9-8 15:00:00.000000+03:00
Not worked时区是不同的,为什么?我对两个对象使用相同的时区。如何将时区设置为+03:00 (这是伊斯坦布尔的时区)?谢谢。
发布于 2020-09-08 21:18:13
代码无法工作,因为您需要使用tzinfo=.:
ed = datetime.datetime(2020, 9, 8, 15, 0, tzinfo=pytz.timezone(userInfo))但结果却是错误的。我不知道为什么,但要想得到你想要的,就用这个表格:
ed = pytz.timezone(userInfo).localize(datetime.datetime(2020, 9, 8, 15, 0))想了解更多信息,请看这篇文章:pytz - Converting UTC and timezone to local time
https://stackoverflow.com/questions/63800936
复制相似问题