In Python, how to print FULL ISO 8601 timestamp, including current timezone

2024/9/24 13:24:24

I need to print the FULL local date/time in ISO 8601 format, including the local timezone info, eg:

2007-04-05T12:30:00.0000-02:00

I can use datetime.isoformat() to print it, if I have the right tzinfo object - but how do I get that?

Note, I'm stuck at Python 2.5, which may reduce some availability of options.

Answer

The python standard library does not provide tzinfo implementation. You need to subclass it. examples are provided in the datetime module.

The accepted answer provide wrong results. For example in my timezone +02, the result is +01:59. This is because microsecond replacement to 0 needs to be done on localnow and utcnow before the difference is calculated.

Here a version of mine for python 2.5:

# coding=utf-8def isoformat_offset(dt, offset, dt_sep='T', hm_sep=True, short=True):"""Return a string representing the date and time in ISO 8601 format,YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM. If microseconds is 0 .mmmmmm is omitted.The optional argument dt_sep (default 'T') is a one-character separator,placed between the date and time portions of the result.The optional argument hm_Sep (default True) indicates if a : separatorshould be placed between the hours and minutes portions of the time zonedesignator.The optional argument short (default True) defines if the minute portion ofthe time zone designator should be omitted in the case of zero minutes.>>> from datetime import datetime>>> cur = datetime(2017, 4, 26, 17, 14, 23, 123456)>>> off = 2 * 3600 # +02:00>>> isoformat_offset(cur, off)'2017-04-26T17:14:23.123456+02'>>> isoformat_offset(cur, off, ' ')'2017-04-26 17:14:23.123456+02'>>> isoformat_offset(cur, off, hm_sep=False)'2017-04-26T17:14:23.123456+02'>>> isoformat_offset(cur, off, short=False)'2017-04-26T17:14:23.123456+02:00'>>> isoformat_offset(cur, off, hm_sep=False, short=False)'2017-04-26T17:14:23.123456+0200'>>> cur = cur.replace(microsecond=0)>>> isoformat_offset(cur, off)'2017-04-26T17:14:23+02'>>> off = -2 * 3600 # -02:00>>> isoformat_offset(cur, off)'2017-04-26T17:14:23-02'>>> off = 2 * 3600 + 30 * 60 # +02:30>>> isoformat_offset(cur, off)'2017-04-26T17:14:23+02:30'>>> isoformat_offset(cur, off, hm_sep=False)'2017-04-26T17:14:23+0230'"""offset_hours = offset // 3600offset_mins = (offset - offset_hours * 3600) // 60frmt = '%s%+03d'args = [dt.isoformat(dt_sep), offset_hours]if (short is True and offset_mins > 0) or (short is False and offset_mins == 0):if hm_sep is True:frmt += ':'frmt += '%02d'args.append(offset_mins)return frmt % tuple(args)if __name__ == '__main__':import doctestdoctest.testmod()

To get the local timezone in seconds as need for this function, use negated altzone from time module:

from datetime import datetime
import timenow = datetime.now()
offset = -time.altzone
print(isoformat_offset(now, offset))
https://en.xdnf.cn/q/71699.html

Related Q&A

TextVariable not working

I am trying to get the Text out of an Entry widget in Tkinter. It works with Entry1.get(), but it does not work using textvariableWhat am I doing wrong ? from Tkinter import * master = Tk() v = String…

Is there a Python module to get next runtime from a crontab-style time definition?

Im writing a dashboard application and I need a way to figure out how long an item is "valid", i.e. when should it have been superseded by a new value (its possible to have an error such that…

Django Generic Relations error: cannot resolve keyword content_object into field

Im using Djangos Generic Relations to define Vote model for Question and Answer models. Here is my vote model:models.pyclass Vote(models.Model):user_voted = models.ForeignKey(MyUser)is_upvote = models.…

How to benchmark unit tests in Python without adding any code

I have a Python project with a bunch of tests that have already been implemented, and Id like to begin benchmarking them so I can compare performance of the code, servers, etc over time. Locating the …

Digit recognition with Tesseract OCR and python

I use Tesseract and python to read digits (from a energy meter). Everything works well except for the number "1". Tesseract can not read the "1" Digit.This is the picture I send t…

Pycharm not recognizing packages even when __init__.py exits

This is my directory structure--> ProjectDirectory-->__init__.py--> BaseDirectory-->__init__.py--> AnotherBaseDirectory-->__init__.py-->program.pyinside program.pyWhen i give impor…

Scrapy is following and scraping non-allowed links

I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:http://example.com/YYYY/DDDD/index.htm where YYYY is the …

Overriding virtual methods in PyGObject

Im trying to implement the Heigh-for-width Geometry Management in GTK with Python for my custom Widget. My widget is a subclass from Gtk.DrawingArea and draws some parts of an Image.As I understood the…

How to find if two numbers are consecutive numbers in gray code sequence

I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the …

How do I get data from selected points in an offline plotly python jupyter notebook?

Example code:from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.graph_objs as goimport numpy as npN = 30 random_x = np.random.randn(N) random_y = np.random.randn…