For those looking to match datetime's ISO 8601-compliant isoformat:
from datetime import datetime
now = datetime.now()
isoformat = now.isoformat()
diy_isoformat = now.strftime("%Y-%m-%dT%H:%M:%S.%f")
assert isoformat == diy_isoformat
print(isoformat)
Will print:
2022-06-17T15:33:08.893344
Answer from Intrastellar Explorer on Stack OverflowFor those looking to match datetime's ISO 8601-compliant isoformat:
from datetime import datetime
now = datetime.now()
isoformat = now.isoformat()
diy_isoformat = now.strftime("%Y-%m-%dT%H:%M:%S.%f")
assert isoformat == diy_isoformat
print(isoformat)
Will print:
2022-06-17T15:33:08.893344
That can work for you:
Convert UTC datetime string to local datetime
I copied the code to make it easier to tackle, I indicate it's another person's answer anyway.
from datetime import datetime,tzinfo,timedelta
class Zone(tzinfo):
def __init__(self,offset,isdst,name):
self.offset = offset
self.isdst = isdst
self.name = name
def utcoffset(self, dt):
return timedelta(hours=self.offset) + self.dst(dt)
def dst(self, dt):
return timedelta(hours=1) if self.isdst else timedelta(0)
def tzname(self,dt):
return self.name
GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')
print(datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z'))
print(datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z'))
print(datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z'))
t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print(t)
print(t.astimezone(EST))
I've tried it in my Python Notebook and works perfectly.
datetime - ISO time (ISO 8601) in Python - Stack Overflow
PSA: As of Python 3.11, `datetime.fromisoformat` supports most ISO 8601 formats (notably the "Z" suffix)
Add ISO Basic format support to datetime.isoformat() and date.isoformat()
datetime - How do you convert a python time.struct_time object into a ISO string? - Stack Overflow
Videos
Local to ISO 8601:
import datetime
datetime.datetime.now().isoformat()
>>> '2024-08-01T14:38:32.499588'
UTC to ISO 8601:
import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:38:47.731215+00:00'
Local to ISO 8601 without microsecond:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:38:57'
UTC to ISO 8601 with timezone information (Python 3):
import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:39:06.274874+00:00'
Local to ISO 8601 with timezone information (Python 3):
import datetime
datetime.datetime.now().astimezone().isoformat()
>>> '2024-08-01T14:39:16.698776+10:00'
Local to ISO 8601 with local timezone information without microsecond (Python 3):
import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:39:28+10:00'
Notice there is a bug when using astimezone() on utcnow(). This gives an incorrect result:
datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result, do not use.
.utcnow() is deprecated, use .now(datetime.timezome.utc) instead.
For Python 2, see and use pytz.
ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:
>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'
If you don't need the microseconds, just leave out the .%f part:
>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'
For local time:
>>> datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5))).strftime("%Y-%m-%dT%H:%M:%S%:z")
'2018-09-05T14:09:03-05:00'
In general, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:
>>> datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'
In Python 3.10 and earlier, datetime.fromisoformat only supported formats outputted by datetime.isoformat. This meant that many valid ISO 8601 strings could not be parsed, including the very common "Z" suffix (e.g. 2000-01-01T00:00:00Z).
I discovered today that 3.11 supports most ISO 8601 formats. I'm thrilled: I'll no longer have to use a third-party library to ingest ISO 8601 and RFC 3339 datetimes. This was one of my biggest gripes with Python's stdlib.
It's not 100% standards compliant, but I think the exceptions are pretty reasonable:
-
Time zone offsets may have fractional seconds.
-
The T separator may be replaced by any single unicode character.
-
Ordinal dates are not currently supported.
-
Fractional hours and minutes are not supported.
https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat
» pip install isodate
Using time.strftime() is perhaps easiest:
iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
Demo:
>>> import time
>>> timetup = time.gmtime()
>>> time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
'2013-10-11T13:31:03Z'
You can also use a datetime.datetime() object, which has a datetime.isoformat() method:
>>> from datetime import datetime
>>> datetime(*timetup[:6]).isoformat()
'2013-10-11T13:31:03'
This misses the timezone Z marker; you could just add that.
iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup)
The last format charater ‘Z’ is not necessary, such as
iso = time.strftime('%Y-%m-%dT%H:%M:%S', timetup)
You will get time string like '2015-11-05 02:09:57'