Dev
Dev

Reputation: 13773

timezone offset in datetime format in python 3.6

This code is working on python 3.7 and failing on 3.6

from datetime import datetime
try:
    d = datetime.strptime('2019-07-30T00:00:00.000-05:00', '%Y-%m-%dT%H:%M:%S.%f%z')
    print(d)

except ValueError as ve:
    print(str(ve))

ValueError: time data '2019-07-30T00:00:00.000-05:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

What's the format for timezone offset e.g. -05:00 in python 3.6?

Upvotes: 1

Views: 9829

Answers (2)

Muskan Jain
Muskan Jain

Reputation: 11

The format in 3.6 is ±HHMM[SS[.ffffff]]. You can convert your string

time_str = "2019-07-30T00:00:00.000-05:00"
time_str = time_str[0:-3]+time_str[-2:] 

Upvotes: 1

MyNameIsCaleb
MyNameIsCaleb

Reputation: 4489

From the docs:

For an aware object:

%z utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds. The ffffff part is omitted when the offset is a whole number of seconds and both the ffffff and the SS part is omitted when the offset is a whole number of minutes. For example, if utcoffset() returns timedelta(hours=-3, minutes=-30), %z is replaced with the string '-0330'.

Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes.

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

%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.

Which means that in 3.6 you would be restricted to a whole number for offset and that you need to remove the colon before 3.7 so:

d = datetime.strptime('2019-07-30T00:00:00.000-0500', '%Y-%m-%dT%H:%M:%S.%f%z')

Upvotes: 4

Related Questions