datetime.strptime strange behavior [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-02 04:30:08

See this discussion on the official Python bug tracker. Apparently %Z only supports UTC, GMT and the local time zone (as returned by time.tzname).

It's an interesting case, the official Python docs are misleading (to put it nicely):

%Z Time zone name (empty string if the object is naive).(empty), UTC, EST, CST

This is wrong. %Z will only recognise EST, CST, etc. if they are the local timezone of the OS.

EDIT Well, there is a note near the bottom of the page in the docs that says

%Z If tzname() returns None, %Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string.

Still, not as clear as it could be.

To make it clear:

It works on your local machine because it uses IDT as its local timezone, which is not the case for the AWS remote machine.

datetime.datetime.strptime("IDT", "%Z")

produces an error

ValueError: time data 'IDT' does not match format '%Z'

as %Z does not support IDT (Israel Daylight Time).

The solution depend on what you're doing with the data next. If you use pytz and ignore the 'IDT' part of the date strings you're stripping the time from, then you can store then while recording the timezone.

dt = datetime.datetime.strptime("Fri, 23 Aug 2019 20:24:46", "%a, %d %b %Y %H:%M:%S")
print(dt)

2019-08-23 20:24:46

whereas

import pytz
idt = pytz.timezone('Israel')
dt_idt = dt.astimezone(idt)
print(dt_idt)

2019-08-23 22:24:46+03:00

is more utile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!