Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an RFC 3339 time to a standard Python timestamp

Is there an easy way to convert an RFC 3339 time into a regular Python timestamp?

I've got a script which is reading an ATOM feed and I'd like to be able to compare the timestamp of an item in the ATOM feed to the modification time of a file.

I notice from the ATOM spec, that ATOM dates include a time zone offset (Z<a number>) but, in my case, there's nothing after the Z so I guess we can assume GMT.

I suppose I could parse the time with a regex of some sort but I was hoping Python had a built-in way of doing it that I just haven't been able to find.

like image 530
Mark Biek Avatar asked Dec 21 '09 19:12

Mark Biek


People also ask

How do I get the exact timestamp in Python?

To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.


Video Answer


1 Answers

You don't include an example, but if you don't have a Z-offset or timezone, and assuming you don't want durations but just the basic time, then maybe this will suit you:

import datetime as dt >>> dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f') datetime.datetime(1985, 4, 12, 23, 20, 50, 520000) 

The strptime() function was added to the datetime module in Python 2.5 so some people don't yet know it's there.

Edit: The time.strptime() function has existed for a while though, and works about the same to give you a struct_time value:

>>> ts = time.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f') >>> ts time.struct_time(tm_year=1985, tm_mon=4, tm_mday=12, tm_hour=23, tm_min=20, tm_sec=50, tm_wday=4, tm_yday=102, tm_isdst=-1) >>> time.mktime(ts) 482210450.0 
like image 96
Peter Hansen Avatar answered Sep 22 '22 02:09

Peter Hansen