Timestamped Python Reader Log File Including Microseconds

I have a timestamp in a log file with a format such as:

2010-01-01 18:48:14.631829

I tried the usual suspects like strptime, and no matter what I do, I understand that it does not match the format I specified. ("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")

I even tried to split the value into. so I can just compare vs a value that has no microseconds on it, but STILL tells me that it does not match: "% Y-% m-% d% H:% M:% S"

Ug, all I have to do is a simple delta of time, haha. Why is python time so scattered? time, date and time, other various types of imports

+3
source share
3 answers

You can use the strptimesame (only for Python 2.6+):

>>> import datetime
>>> s = "2010-01-01 18:48:14.631829"
>>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2010, 1, 1, 18, 48, 14, 631829)

: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

...

%f [0,999999],

...

2.5 - , :

>>> import re
>>> datetime.datetime.strptime(re.sub('\..*', '', s), "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 1, 1, 18, 48, 14)
+4

, :

>>> print s
2010-01-01 18:48:14.631829
>>> time.strptime(s.split('.')[0], "%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2010, tm_mon=1, tm_mday=1, tm_hour=18, tm_min=48, tm_sec=14, tm_wday=4, tm_yday=1, tm_isdst=-1)
>>> 
0

Works for me (Python 2.6):

>>> import datetime
>>> string1 = '2010-01-01 18:48:14.631829'
>>> string2 = '2010-01-09 13:04:39.540268'
>>> time1 = datetime.datetime.strptime(string1, '%Y-%m-%d %H:%M:%S.%f')
>>> time2 = datetime.datetime.strptime(string2, '%Y-%m-%d %H:%M:%S.%f')
>>> time2 - time1
datetime.timedelta(7, 65784, 908439)

those. between the two dates there are 7 days, 65784 seconds and 908439 microseconds. For information about the object, timedeltasee datetime docs .

Edit: Try the following if you cannot use the directive %f:

>>> time1 = datetime.datetime.strptime(string1.split('.')[0], '%Y-%m-%d %H:%M:%S')
>>> time2 = datetime.datetime.strptime(string2.split('.')[0], '%Y-%m-%d %H:%M:%S')
>>> time2 - time1
datetime.timedelta(7, 65785)
0
source

All Articles