strptime() %f directive can't handle more than 6 decimal places

Viewed 265

I'm trying to parse this object which comes from a C# DateTime object, then serialized to JSON:

{ "date": "2021-02-18T19:35:19.6472822+01:00", "value": 8, "temp": 7 }

I'm using this in Python to parse it:

from datetime import datetime as dt    
date_obj = dt.strptime('2021-02-18T19:35:19.6472822+01:00', '%Y-%m-%dT%H:%M:%S.%f%z')

That Python code works when the decimal places are fewer than 7.

This is the error I get:

Exception <class 'ValueError'> raised: time data '2021-02-18T19:35:19.6472822+01:00' 
does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

Is there another way to parse this string in Python?

1 Answers

You can use pandas in that case

import pandas as pd
a='2021-02-18T19:35:19.6472822+01:00'
pd.to_datetime(a, format='%Y-%m-%dT%H:%M:%S.%f')

Output:

Timestamp('2021-02-18 19:35:19.647282200+0100', tz='pytz.FixedOffset(60)')
Related