89

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

Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512
  • Just found this similar question: [ISO Time (ISO 8601) in Python?](http://stackoverflow.com/questions/2150739/iso-time-iso-8601-in-python) – Yarin Dec 19 '11 at 04:05
  • [Further down](http://docs.python.org/library/datetime.html#tzinfo-objects) in the same doc that you linked to, it explains how to implement it, giving some examples, including full code for a `UTC` class (representing UTC), a `FixedOffset` class (representing a timezone with a fixed offset from UTC, as opposed to a timezone with DST and whatnot), and a few others. – ruakh Dec 19 '11 at 02:38
  • @ruakh- thanks, I missed those examples- The `LocalTimezone()` class did the trick. – Yarin Dec 19 '11 at 03:34

7 Answers7

88

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'

zenbeni
  • 7,019
  • 3
  • 29
  • 60
monkut
  • 42,176
  • 24
  • 124
  • 155
45

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 1
    Hands down, best answer for Python 3.3+ – markos.aivazoglou Nov 15 '16 at 13:59
  • Technically, ISO 8601 and RFC 3339 aren't 100% compatible...some differences exist, such as that ISO 8601 allows either a minus sign or a hyphen for the UTC offset part, whereas RFC 3339 _only_ allows a hyphen. Every `.isoformat()` implementation I've seen so far (only a couple) does overlap with RFC 3339, but it's good to make yourself aware of the differences – villapx Nov 21 '16 at 20:21
  • 2
    @villapx: rfc 3339 is a profile of ISO 8601. It happens that `datetime.isoformat()` is RFC 3339 for a timezone-aware datetime (that is why I've used it). – jfs Nov 21 '16 at 20:27
  • @J.F.Sebastian Yeah, it seems you're right...from the docs, `isotime()` `[gives] the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM`, which is RFC 3339. It doesn't explicitly say it will use a hyphen as opposed to a minus sign, but it's implied by the examples – villapx Nov 21 '16 at 22:20
  • Although, `isoformat()` doesn't look at the daylight savings time offset for the `tzinfo` object--as I change the `dst()` return value, `isoformat()` still returns the same string – villapx Nov 22 '16 at 14:22
  • @villapx: `isoformat()` returns the correct value It just reflects what `datetime` object contains. Namely, it shows its `.utcoffset()` value. – jfs Nov 22 '16 at 14:39
  • @J.F.Sebastian Right, that's what I mean--just wanted to make potential users aware that `isoformat()` isn't aware of DST – villapx Nov 22 '16 at 16:00
  • 1
    @villapx: no, it is wrong. You are misleading the "potential users". If `.utcoffset()` doesn't reflect `.dst()` value then your `datetime` class is broken. – jfs Nov 22 '16 at 16:18
  • 1
    @J.F.Sebastian Oh wow, you're right. I was totally misled by the `datetime.tzinfo.dst()` [documentation](https://docs.python.org/2.7/library/datetime.html#datetime.tzinfo.dst): `Note that DST offset, if applicable, has already been added to the UTC offset returned by utcoffset(), so there’s no need to consult dst() unless you’re interested in obtaining DST info separately.` I did not see directly above that, for `utcoffset()`, where it says, `"Note that this is intended to be the total offset from UTC."` – villapx Nov 22 '16 at 16:24
  • Can't it be just `datetime.datetime.now().astimezone().isoformat()`? `now()` returns a naive object and `astimezone()` sets the local timezone. – jrc May 25 '21 at 13:39
  • 1
    @jrc: now() by itself may be ambiguous (e.g., during a DST transition). – jfs May 26 '21 at 15:15
14

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.

JJC
  • 9,547
  • 8
  • 48
  • 53
  • Actually the Python datetime is not compatible with ISO 8601, as it doesn't allow strings ending with 'Z' – asu Aug 23 '20 at 14:16
  • Exactly. How can I get the Z ending though? – uwieuwe4 Jul 13 '21 at 12:25
  • 4
    @uwieuwe4 you can just use `.replace('+00:00', 'Z')` on the above result. Or, just use `.strftime('%Y-%m-%dT%H:%M:%SZ')` instead of .isoformat(). – JJC Jul 13 '21 at 15:41
  • Python 3.11 can now parse datetimes with Z suffix: https://docs.python.org/3/whatsnew/3.11.html#datetime – HTE Aug 12 '23 at 16:15
10

I struggled with RFC3339 datetime format a lot, but I found a suitable solution to convert date_string <=> datetime_object in both directions.

You need two different external modules, because one of them is is only able to do the conversion in one direction (unfortunately):

first install:

sudo pip install rfc3339
sudo pip install iso8601

then include:

import datetime     # for general datetime object handling
import rfc3339      # for date object -> date string
import iso8601      # for date string -> date object

For not needing to remember which module is for which direction, I wrote two simple helper functions:

def get_date_object(date_string):
  return iso8601.parse_date(date_string)

def get_date_string(date_object):
  return rfc3339.rfc3339(date_object)

which inside your code you can easily use like this:

input_string = '1989-01-01T00:18:07-05:00'
test_date = get_date_object(input_string)
# >>> datetime.datetime(1989, 1, 1, 0, 18, 7, tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>)

test_string = get_date_string(test_date)
# >>> '1989-01-01T00:18:07-05:00'

test_string is input_string # >>> True

Heureka! Now you can easily (haha) use your date strings and date strings in a useable format.

MenschMarcus
  • 507
  • 5
  • 12
1

The pytz package is available for Python 2.X and 3.X. It implements concrete subclasses of tzinfo, among other services, so you don't have to.

To add a UTC offset: import datetime import pytz

dt = datetime.datetime(2011, 12, 18, 20, 46, 00, 392227)
utc_dt = pytz.UTC.localize(dt)

And now this:

print utc_dt.isoformat()

would print:

2011-12-18T20:46:00.392227+00:00
Eli_B
  • 163
  • 2
  • 10
  • you don't need `pytz` module if all you want is UTC timezone. It is simple to [define utc tzinfo](http://stackoverflow.com/a/25421145/4279) – jfs May 19 '15 at 20:36
  • Thanks. I'll save your answer for when I need an stdlib solution. UTC was just the shortest to demonstrate. OP didn't specifically ask for it. `pytz` knows about all timezones and their DST, which I find useful. – Eli_B May 20 '15 at 07:38
  • Note: [`get_localzone()` in my answer](http://stackoverflow.com/a/27987813/4279) returns puts timezone that corresponds to the local timezone. – jfs May 20 '15 at 07:54
  • Yes. It should be" `pytz` timezone", not "`puts ` timezone" – jfs May 20 '15 at 18:24
1

Another useful utility I just started working with: dateutil library for timezone handling and date parsing. Recommended around SO, including this answer

Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512
  • `dateutil` is a library that offers functionality for *parsing* dates to datetime, I don't think this is helpful in the context of *generating* date/time strings with a certain format. – FObersteiner Nov 18 '21 at 14:49
0

You can indeed use the built-in datetime module. As @ruakh mentions, there are examples in the page that show how. If you look into the section on tzinfo you'll see a long example showing many different use cases. Here's the code for the one you're looking for, which is to generate an RFC 3339 UTC timestamp.

from datetime import tzinfo, timedelta, datetime
import time as _time

ZERO = timedelta(0)
STDOFFSET = timedelta(seconds=-_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds=-_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET


class LocalTimezone(tzinfo):

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

Local = LocalTimezone()

d = datetime.now(Local)
print d.isoformat('T')

# which returns
# 2014-04-28T15:44:45.758506-07:00
Community
  • 1
  • 1
gene_wood
  • 1,960
  • 4
  • 26
  • 39