Why does datetime give different timezone formats for the same timezone?
1 2 3 4 5 6 7 | >>> now = datetime.datetime.now(pytz.timezone('Asia/Tokyo')) >>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo')) >>> now datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>) >>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.timezone('Asia/Tokyo')) >>> dt datetime.datetime(2018, 9, 7, 16, 9, 24, 177751, tzinfo=<DstTzInfo 'Asia/Tokyo' LMT+9:19:00 STD>) |
对于
当我比较他们不同的时间时:
1 2 | >>> now == dt False |
如何将
如相关问题的答案所述,永远不要使用datetime()创建带有时区信息的日期时间。 相反,在使用UTC创建日期时,应使用
1 2 3 4 5 6 7 8 9 10 11 12 | >>> import pytz >>> from datetime import datetime >>> >>> now = datetime.now(pytz.utc) >>> dt = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, pytz.utc) >>> jst = pytz.timezone('Asia/Tokyo') >>> jst.normalize(now) datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>) >>> jst.normalize(dt) datetime.datetime(2018, 9, 7, 20, 21, 44, 653897, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>) >>> now == dt True |