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 tell开发者_如何学运维s 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
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)
Of course, splitting the string does work:
>>> 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)
>>>
The following 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)
i.e., there are 7 days, 65784 seconds and 908439 microseconds between the two dates. See the datetime docs for information on the timedelta
object.
Edit: Try the following if you cannot use the %f
directive:
>>> 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)
精彩评论