"python: converting string to timestamp with microseconds" Code Answer

2

there is no slot for the microseconds component in a time tuple:

>>> import time
>>> import datetime
>>> mydate = "2014-08-01 04:41:52,117"
>>> datetime.datetime.strptime(mydate, "%y-%m-%d %h:%m:%s,%f").timetuple()
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)

you'll have to add those manually:

>>> dt = datetime.datetime.strptime(mydate, "%y-%m-%d %h:%m:%s,%f")
>>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
1406864512.117

the other method you could follow is to produce a timedelta() object relative to the epoch, then get the timestamp with the timedelta.total_seconds() method:

epoch = datetime.datetime.fromtimestamp(0)
(dt - epoch).total_seconds()

the use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. this method can be inaccurate based on the history of your local timezone however, see j.f. sebastian's comment. you'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.

as such, it is easier to stick to the timetuple() + microseconds approach.

demo:

>>> dt = datetime.datetime.strptime(mydate, "%y-%m-%d %h:%m:%s,%f")
>>> epoch = datetime.datetime.fromtimestamp(0)
>>> (dt - epoch).total_seconds()
1406864512.117
By smatthewenglish on September 15 2022

Answers related to “python: converting string to timestamp with microseconds”

Only authorized users can answer the Search term. Please sign in first, or register a free account.