Python date format rfc3339

Generate RFC 3339 timestamp in Python

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' 

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

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

d = datetime.datetime.utcnow() #  

Solution 2

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

Solution 4

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

sudo pip install rfc3339 sudo pip install iso8601 
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=) 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.

Solution 5

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

Python Tutorial: Datetime Module - How to work with Dates, Times, Timedeltas, and Timezones

Python SAP NW RFC SDK part2

#73: Pandas (Part 50): Timestamp in Python with pd.Timestamp() | Tutorial

#75: Pandas (Part 52): Create Timestamp in Python using pd.date_range() | Tutorial

#77: Pandas (Part 54): Create Timestamp in Python using pd.period() | Tutorial

Python: Dates, Times & Timestamps Part-1 | datetime, time libraries

PYTHON : Generate RFC 3339 timestamp in Python

Python with OANDA's API | Pricing, Trading

How to date/timestamp in new or existing file name in python

Generate RFC 3339 timestamp in Python - PYTHON

Yarin

Products PDF Buddy - Popular online PDF editor Gems Snappconfig - Smarter Rails app configuration

Comments

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

Further down 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.

Источник

pyrfc3339.generator – Generate RFC 3339 timestamps¶

The timestamp will use UTC unless utc=False is specified, in which case it will use the timezone from the datetime.datetime ’s tzinfo parameter.

>>> eastern = pytz.timezone('US/Eastern') >>> dt = eastern.localize(datetime(2009,1,1,12,59,59)) >>> generate(dt) '2009-01-01T17:59:59Z' >>> generate(dt, utc=False) '2009-01-01T12:59:59-05:00' 

Unless accept_naive=True is specified, the datetime must not be naive.

>>> generate(datetime(2009,1,1,12,59,59,0)) Traceback (most recent call last): . ValueError: naive datetime and accept_naive is False 
>>> generate(datetime(2009,1,1,12,59,59,0), accept_naive=True) '2009-01-01T12:59:59Z' 

If accept_naive=True is specified, the datetime is assumed to be UTC. Attempting to generate a local timestamp from a naive datetime will result in an error.

>>> generate(datetime(2009,1,1,12,59,59,0), accept_naive=True, utc=False) Traceback (most recent call last): . ValueError: cannot generate a local timestamp from a naive datetime 

© Copyright 2019, Kurt Raschke Revision 99255c9b .

Versions latest stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

RFC #822 and RFC #3339 dates in Python

When adding a JSON feed and an RSS feed to tumblelog I needed a publication date and time for each article published. As I don't have an actual publication time I decided to use the end of day, as explained in A Matter of Time.

Edit: this blog post has been updated with additional code to make the RFC #822 solution work for a non-USA locale.

The end of day

In order to obtain a datetime Python object for the local end of day for a given date I came up with the following idea:

  • parse the date with a time of 23:59:59 attached to it
  • create a new object using this result but in the local time zone using the astimezone constructor

I accomplished this in Python as follows:

def get_end_of_day(date): return datetime.strptime( f' 23:59:59', '%Y-%m-%d %H:%M:%S').astimezone() 

Calling this function with the date of today returns:

>>> get_end_of_day('2019-10-09') datetime.datetime(2019, 10, 9, 23, 59, 59, tzinfo=datetime.timezone(datetime.tim edelta(seconds=7200), 'CEST')) 

Note the additional time zone data ( tzinfo ); Central European Summer Time, which is correct for my location.

RFC #822

For the RSS feed I needed the pubDate to be in RFC #822 format, which I obtained as follows:

ctime = end_of_day.ctime() pub_date = (f', ' + end_of_day.strftime(' %Y %H:%M:%S %z')) 

Note that the short month name and the short day name are obtained from ctime instead of returned by strftime . The reason for this is that ctime returns those names in the USA locale, a requirement for RFC #822.

Moreover, it's tempting to use %Z instead of %z but note that, for example, CEST is not valid according to the RSS feed validator, which refers to section 5.1 of RFC #822. Hence, why digits must be used instead for a general solution.

An example of a pub_date value is:

Wed, 09 Oct 2019 23:59:59 +0200 

RFC #3339

For the JSON feed I needed a date_published in RFC #3339 format, which was even easier to obtain as the string version of a datetime is correct except for a space instead of a T :

date_published = str(end_of_day).replace(' ', 'T') 

An example of a date_published value is:

See Also

  • datetime — Basic date and time types
  • RFC #822 — Standard for ARPA Internet Text Messages
  • RFC #3339 — Date and Time on the Internet: Timestamps
  • Hand coding an RSS 2.0 feed in Python
  • RFC #822 and RFC #3339 dates in Perl

Источник

rfc3339.py

rfc3339.py is a small Python library to format dates to rfc 3339 strings. Useful if you want to add an Atom feed to you site / project. Grab the file, drop it in your python source code, that's it! Licensed under the term of the ISC License a simple, permissive, BSD-like license.

Additionally, you can also install it from PyPi: pip install rfc3339 or easy_install rfc3339 .

If you find any bugs or would like to see something added, feel free to open a ticket on BitBucket.

>>> import time >>> timestamp = time.time() >>> print timestamp 1220939251.89 >>> import datetime >>> d = datetime.datetime.fromtimestamp(timestamp) >>> print d 2008-09-08 22:47:31.893205 

>>> from rfc3339 import rfc3339

>>> rfc3339(timestamp) # Works with timestamps '2008-09-08T22:47:31-07:00'

>>> rfc3339(d) # And datetime & date objects '2008-09-08T22:47:31-07:00'

>>> rfc3339(d, utc=True) # Normalize time to UTC '2008-09-08T15:47:31Z' >>> rfc3339(d, utc=True, use_system_timezone=False) '2008-09-08T22:47:31Z'

2010-2-5: Handle system timezone correctly. Instead of using the current daylight saving, use the the daylight saving at the time of the datetime object.

2009-12-21: Fixed a bug with daylight savings. Reported by Gary Bishop.

2010-1-26: I've changed the license from “Public domain” to the ISC License.

2011-1-4: Fixed a bug with dates before 1970.

Documentation

Wow! I also made some docs! Generated via pydoc rfc3339

Help on module rfc3339: 

NAME rfc3339

DESCRIPTION The function rfc3339 formats dates according to the :RFC:3339. rfc3339 tries to have as much as possible sensible defaults.

FUNCTIONS rfc3339(date, utc=False, use_system_timezone=True) Return a string formatted according to the :RFC:3339. If called with utc=True, it normalizes date to the UTC date. If date does not have any timezone information, uses the local timezone::

 >>> date = datetime.datetime(2008, 4, 2, 20) >>> rfc3339(date, utc=True, use_system_timezone=False) '2008-04-02T20:00:00Z' >>> rfc3339(date) # doctest: +ELLIPSIS '2008-04-02T20:00:00. ' If called with `user_system_time=False` don't use the local timezone if `date` does not have timezone informations and consider the offset to UTC to be zero:: >>> rfc3339(date, use_system_timezone=False) '2008-04-02T20:00:00+00:00' `date` must be a `datetime.datetime`, `datetime.date` or a timestamp as returned by `time.time()`:: >>> rfc3339(0, utc=True, use_system_timezone=False) '1970-01-01T00:00:00Z' >>> rfc3339(datetime.date(2008, 9, 6), utc=True, . use_system_timezone=False) '2008-09-06T00:00:00Z' >>> rfc3339(datetime.date(2008, 9, 6), . use_system_timezone=False) '2008-09-06T00:00:00+00:00' >>> rfc3339('foo bar') Traceback (most recent call last): . TypeError: excepted datetime, got str instead 

DATA all = ('rfc3339',) author = 'Henry Precheur ' license = 'ISCL' version = '3'

Источник

Читайте также:  Html теги расположение таблицы
Оцените статью