views:

140

answers:

4

I want to parse a timestamp from a log file that has been written via

datetime.datetime.now().strftime('%Y%m%d%H%M%S')

and then compute the number of seconds that have passed since this timestamp.

I know I could do it with datetime.datetime.strptime to get back a datetime object and then compute a timedelta. Problem is, the strptime function has been introduced with Python 2.5 and I'm using Python2.4.4 (an upgrade is not possible in my context).

Any easy way to do this?

A: 

There is a strptime function in the time module in python 2.4 already. You'd have to convert that to a datetime object for example via the detour of the unix timestamp, don't know if there's a better way.

Marian
+1  A: 
now = datetime.datetime.now()
then = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6])
difference = now - then
Matthew Flaschen
+2  A: 
>>> ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S'))
>>> ts
1081809951.0
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2004, 4, 12, 23, 45, 51)
SilentGhost
A: 

There's also mx.DateTime which is now free to use and it quite a bit easier to deal with and more flexible than Python's built in datetime module for well just about everything. Works in python 2.3+ No * and [0:6] shenanigans required.

Egenix Download

>>> import mx.DateTime as dt
>>> then = dt.DateTimeFrom(dt.strptime('20040412234551', '%Y%m%d%H%M%S'))
>>> delta = dt.now() - then
>>> delta
<DateTimeDelta object for '2247:13:09:22.31' at 2ab37d666b58>
>>> delta.hours
53941.156198977762
>>> delta.days
2247.5481749574069
Khorkrak