Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate RFC 3339 timestamp in Python [duplicate]

I'm trying to generate an RFC 3339 UTC timestamp in Python. So far I've been able to do the following:

>>> d = datetime.datetime.now() >>> print d.isoformat('T') 2011-12-18T20:46:00.392227 

My problem is with setting the UTC offset.

According to the docs, the classmethod datetime.now([tz]), takes an optional tz argument where tz must be an instance of a class tzinfo subclass, and datetime.tzinfo is an abstract base class for time zone information objects.

This is where I get lost- How come tzinfo is an abstract class, and how am I supposed to implement it?


(NOTE: In PHP it's as simple as timestamp = date(DATE_RFC3339);, which is why I can't understand why Python's approach is so convoluted...)

like image 714
Yarin Avatar asked Dec 19 '11 01:12

Yarin


People also ask

How do you convert UTC to timestamp in Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.


1 Answers

UPDATE 2021

In Python 3.2 timezone was added to the datetime module allowing you to easily assign a timezone to UTC.

>>> import datetime >>> n = datetime.datetime.now(datetime.timezone.utc) >>> n.isoformat() '2021-07-13T15:28:51.818095+00:00' 

previous answer:

Timezones are a pain, which is probably why they chose not to include them in the datetime library.

try pytz, it has the tzinfo your looking for: http://pytz.sourceforge.net/

You need to first create the datetime object, then apply the timezone like as below, and then your .isoformat() output will include the UTC offset as desired:

d = datetime.datetime.utcnow() d_with_timezone = d.replace(tzinfo=pytz.UTC) d_with_timezone.isoformat() 

'2017-04-13T14:34:23.111142+00:00'

Or, just use UTC, and throw a "Z" (for Zulu timezone) on the end to mark the "timezone" as UTC.

d = datetime.datetime.utcnow() # <-- get time in UTC print d.isoformat("T") + "Z" 

'2017-04-13T14:34:23.111142Z'

like image 105
monkut Avatar answered Oct 21 '22 01:10

monkut