Reputation: 979
My gps, via gpsd, spits back a time in the format
time_string = '1582-10-04T12:34:56.000Z'
I can turn this string into a timezone aware datetime
object
with
from datetime import datetime, timedelta, timezone
timeformat = '%Y-%m-%dT%H:%M:%S.000Z' # ISO8601
datetime.strptime(time_string, timeformat).replace(tzinfo=(timezone(timedelta(0))))
...which is cool. I can than manipulate the object, add, subtract, change timezones, calculate a time delta inclusive of a time zone change, etc..
The problem is occasionally some aspect of the application will return a time string with milliseconds attached.
time_string = '1582-10-04T12:34:56.123Z'
...and all hell breaks loose.
.strip('Z')
doesn't do it.
timeformat = '%Y-%m-%dT%H:%M:%S
<--without .000
or .000Z
does not work either as neither b.strip('.000Z')
or permutations thereof.
I can't seem to find an elegant way to save the millisecond(s), if, and when, they occur, and parse the string into a time zone aware datetime object.
Upvotes: 0
Views: 4924
Reputation: 8176
What about replacing the 000
by %f
?
from datetime import datetime, timedelta, timezone
time_string = '1582-10-04T12:34:56.123Z'
timeformat = '%Y-%m-%dT%H:%M:%S.%fZ'
datetime.strptime(time_string, timeformat).replace(tzinfo=(timezone(timedelta(0))))
Output:
datetime.datetime(1582, 10, 4, 12, 34, 56, 123000, tzinfo=datetime.timezone.utc)
see strftime() and strptime() Behavior for %f
format.
Upvotes: 2