Skip to content Skip to sidebar Skip to footer

How Can I Parse '2020-07-30t20:40:33.1000000z' Using Datetime.strptime

I am trying to parse and convert '2020-07-30T20:40:33.1000000Z'in Python: from datetime import datetime Data = [{'id': 'XXXXXXXXXXXXX', 'number': 3, 'externalId': '0000', 'dateCre

Solution 1:

if you really have 7 decimal places of fractional seconds and don't care about the 1/10th of the microseconds, you could use a re.sub and datetime.fromisoformat:

import re
from datetime import datetime 

s = "2020-07-30T20:40:33.1000000Z"
dt = datetime.fromisoformat(re.sub('[0-9]Z', '+00:00', s))

print(dt)
print(repr(dt))
2020-07-3020:40:33.100000+00:00
datetime.datetime(2020, 7, 30, 20, 40, 33, 100000, tzinfo=datetime.timezone.utc)

...or use dateutil's parser:

from dateutil import parser
dt = parser.parse(s)

print(dt)
print(repr(dt))
2020-07-3020:40:33.100000+00:00
datetime.datetime(2020, 7, 30, 20, 40, 33, 100000, tzinfo=tzutc())

...or even pandas's to_datetime, if you maybe work with that lib anyway:

import pandas as pd
dt = pd.to_datetime(s)

print(dt)
print(repr(dt))
2020-07-3020:40:33.100000+00:00
Timestamp('2020-07-30 20:40:33.100000+0000', tz='UTC')

often irrelevant (depending on use-case) but note that convenience costs you some more time:

%timeit datetime.fromisoformat(re.sub('[0-9]Z', '+00:00', s))
1.92 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit parser.parse(s)
79.8 µs ± 3.46 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit pd.to_datetime(s)
62.4 µs ± 1.17 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Post a Comment for "How Can I Parse '2020-07-30t20:40:33.1000000z' Using Datetime.strptime"