Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strptime example for datetime with tz offset

I have the datetime string 2020-10-23T11:50:19+00:00. I can parse it without the timezone as:

>>> datetime.strptime('2020-10-23T11:50:19', '%Y-%m-%dT%H:%M:%S')
datetime.datetime(2020, 10, 23, 11, 50, 19)

But I'm having trouble parsing it with the 00:00 version of the timezone. What would be the correct way to do that?

>>> datetime.strptime('2020-10-23T11:50:19+00:00', '%Y-%m-%dT%H:%M:%S+???')
like image 696
David542 Avatar asked Oct 17 '25 05:10

David542


2 Answers

You're looking for %z:

>>> datetime.strptime('2020-10-23T11:50:19+00:00', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)

Beware of some Python version compatibility notes:

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

More robust approach, it's not strptime, but it's still in stdlib since Python 3.7:

>>> datetime.fromisoformat('2020-10-23T11:50:19+00:00')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)

As documented this function supports strings in the format:

YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

where * can match any single character (not just a T).

like image 119
wim Avatar answered Oct 19 '25 17:10

wim


The dateutil.parser function will parse that timezone format:

from dateutil.parser import parse

dt = parse('2020-10-23T11:50:19+00:00')
print(dt.date())
print(dt.time())
print(dt.tzinfo)

Result:

2020-10-23
11:50:19
tzutc()

You can combine the separate date, time and tzinfo objects into a datetime, if that's what you need, like this:

dt = datetime.combine(dt.date(), dt.time(), tzinfo=dt.tzinfo)
print(dt)

Result:

2020-10-23 11:50:19+00:00
like image 33
CryptoFool Avatar answered Oct 19 '25 17:10

CryptoFool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!