记录下python中的时区问题, 代码如下:
包括datetime.datetime对象使用不同的时区,以及在不同时区间转换。
1 from datetime import datetime 2 3 from dateutil import tz, zoneinfo 4 5 if __name__ == '__main__': 6 zonefile = zoneinfo.get_zonefile_instance() 7 print zonefile.zones.keys()[:20] 8 # use timezone 9 tz_dubai = tz.gettz('Asia/Dubai') 10 tz_sh = tz.gettz('Asia/Shanghai') 11 # Shanghai timezone 12 now_sh = datetime.now(tz=tz_sh) 13 print now_sh 14 # Dubai timezone 15 now_dubai = datetime.now(tz=tz_dubai) 16 print now_dubai 17 # datetime timezone conversion 18 print now_dubai.astimezone(tz_sh) 19 print 'done!'
结果:
['Atlantic/Canary', 'Europe/Lisbon', 'Etc/GMT+9', 'Etc/GMT+8', 'Antarctica/Mawson', 'Etc/GMT+3', 'Etc/GMT+2', 'Etc/GMT+1', 'Etc/GMT+0', 'Etc/GMT+7', 'Etc/GMT+6', 'Etc/GMT+5', 'Etc/GMT+4', 'Indian/Reunion', 'America/Fort_Nelson', 'Antarctica/Davis', 'America/Coral_Harbour', 'Asia/Dhaka', 'America/St_Lucia', 'Australia/LHI'] 2019-01-16 21:15:41.503000+08:00 2019-01-16 17:15:41.503000+04:00 2019-01-16 21:15:41.503000+08:00 done!