Question

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?

Was it helpful?

Solution

>>> 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)

OTHER TIPS

now = datetime.datetime.now()
then = datetime.datetime(*time.strptime('20080227034510' ,'%Y%m%d%H%M%S')[0:6])
difference = now - then

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top