python datetime 时区(timezone) dateutil

时间:2022-11-22 13:17:31

记录下python中的时区问题, 代码如下:

   包括datetime.datetime对象使用不同的时区,以及在不同时区间转换。

 from datetime import datetime

 from dateutil import tz, zoneinfo

 if __name__ == '__main__':
zonefile = zoneinfo.get_zonefile_instance()
print zonefile.zones.keys()[:20]
# use timezone
tz_dubai = tz.gettz('Asia/Dubai')
tz_sh = tz.gettz('Asia/Shanghai')
# Shanghai timezone
now_sh = datetime.now(tz=tz_sh)
print now_sh
# Dubai timezone
now_dubai = datetime.now(tz=tz_dubai)
print now_dubai
# datetime timezone conversion
print now_dubai.astimezone(tz_sh)
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']
-- ::41.503000+:
-- ::41.503000+:
-- ::41.503000+:
done!