Python reading logfile with timestamp including microseconds
You can use strptime
like so (Python 2.6+ only):
>>> 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)
Docs: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
...
%f
Microsecond as a decimal number [0,999999], zero-padded on the left...
If your on 2.5- and you don't care about the micros, you can just chop it off:
>>> import re
>>> datetime.datetime.strptime(re.sub('\..*', '', s), "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 1, 1, 18, 48, 14)
captrap
Updated on June 28, 2022Comments
-
captrap almost 2 years
I've got a timestamp in a log file with the format like:
2010-01-01 18:48:14.631829
I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify.
("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")
I've even tried splitting the value by "." so I can just compare vs the value not having the microseconds on it, but it STILL tells me it doesn't match: "%Y-%m-%d %H:%M:%S"
Ug, all I need to do is a simple time delta, haha. Why is python's time stuff so scattered? time, datetime, other various imports