Skip to content Skip to sidebar Skip to footer

Datetime.strptime Strange Behavior

I'm getting the following error on aws virtual machine running python 3.6.8, while on my laptop it works fine with python 3.6.1 return datetime.strptime(date_str, self.date_form

Solution 1:

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.

Solution 2:

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-2320:24:46

whereas

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

2019-08-2322:24:46+03:00

is more utile.

Post a Comment for "Datetime.strptime Strange Behavior"