Generate RFC 3339 timestamp in Python [duplicate]
Solution 1:
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'
Solution 2:
In Python 3.3+:
>>> from datetime import datetime, timezone
>>> local_time = datetime.now(timezone.utc).astimezone()
>>> local_time.isoformat()
'2015-01-16T16:52:58.547366+01:00'
On older Python versions, if all you need is an aware datetime object representing the current time in UTC then you could define a simple tzinfo subclass as shown in the docs to represent UTC timezone:
from datetime import datetime
utc_now = datetime.now(utc)
print(utc_now.isoformat('T'))
# -> 2015-05-19T20:32:12.610841+00:00
You could also use tzlocal
module to get pytz
timezone representing your local timezone:
#!/usr/bin/env python
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
now = datetime.now(get_localzone())
print(now.isoformat('T'))
It works on both Python 2 and 3.
Solution 3:
On modern (3.x) python, to get RFC 3339 UTC time, all you need to do is use datetime and this single line (no third-party modules necessary):
import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
The result is something like: '2019-06-13T15:29:28.972488+00:00'
This ISO 8601 string is also RFC3339 compatible.