Skip to content
Advertisement

How can I use datetime.strptime on a string in the format ‘0000-00-00T00:00:00+00:00’?

Due to my application’s circumstances, I would prefer to use datetime.strptime instead of dateutil.parser.

After looking at the docs, I thought that %Y-%m-%dT%H:%M:%S%z may be the proper format for parsing a date string like this. Yet it still gives me an error.

Example

from datetime import datetime

d = '0000-00-00T00:00:00+00:00'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')
ValueError: time data '0000-00-00T00:00:00+00:00' does not 
            match format '%Y-%m-%dT%H:%M:%S%z'

Advertisement

Answer

The easiest way to deal with timezones is to use dateutil.parser:

from dateutil.parser import parse
date_obj = parse('1970-01-01T00:00:00+00:00')

date_obj

> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=tzutc())

But you have to pass a valid datetime-value (not only zeros…)

If you want to use strptime(), the timezone has to be in the format 0000 not 00:00, so this works:

d = '1900-02-05T11:43:32+0000'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')

> datetime.datetime(1900, 2, 5, 11, 43, 32, tzinfo=datetime.timezone.utc)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement