How to get time in '2022-12-01T09:13:45Z' this format?
Question:
from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
This doesn’t give me the required format i want
2022-05-18T13:43:13
I wanted to get the time like ‘2022-12-01T09:13:45Z’
Answers:
You can use datime’s strftime function i.e.
current_datetime = datetime.now().replace(microsecond=0)
print(f'ISO Datetime: {current_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")}')
The time format that you want is known as Zulu time format, the following code changes UTC to Zulu format.
Example 1
import datetime
now = datetime.datetime.now()
now = now.replace(tzinfo=datetime.timezone.utc)
print(now)
Output
# 2022-12-01 14:34:42.265501+00:00
Example 2 (Hack)
import datetime
now = datetime.datetime.utcnow()
now = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4] + 'Z'
print(now)
Output
#2022-12-01T08:38:58Z
Hope this helps. Happy Coding 🙂
from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
This doesn’t give me the required format i want
2022-05-18T13:43:13
I wanted to get the time like ‘2022-12-01T09:13:45Z’
You can use datime’s strftime function i.e.
current_datetime = datetime.now().replace(microsecond=0)
print(f'ISO Datetime: {current_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")}')
The time format that you want is known as Zulu time format, the following code changes UTC to Zulu format.
Example 1
import datetime
now = datetime.datetime.now()
now = now.replace(tzinfo=datetime.timezone.utc)
print(now)
Output
# 2022-12-01 14:34:42.265501+00:00
Example 2 (Hack)
import datetime
now = datetime.datetime.utcnow()
now = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4] + 'Z'
print(now)
Output
#2022-12-01T08:38:58Z
Hope this helps. Happy Coding 🙂