-1
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'

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Praveen Kumar
  • 199
  • 11
  • 1
    You want a time with timezone information. so so use `datetime.now(timezone.utc)` – Giacomo Catenazzi Dec 01 '22 at 08:40
  • @FObersteiner: new python support it, else: did yo unotice that the OP is using pytz? So no hack but you the pytz (for old python versions) – Giacomo Catenazzi Dec 01 '22 at 08:45
  • @GiacomoCatenazzi how do you get "Z" for UTC with the standard library? Btw. pytz does not give you any formatting options for converting datetime to string, no? – FObersteiner Dec 01 '22 at 08:47
  • When converting datetime to string, unfortunately, the Python standard library does not provide a built-in method that gives you 'Z' for UTC. You'll need to use one of the "hacks" (append literal Z for instance) below. Or use "+00:00" as a UTC specifier. – FObersteiner Dec 01 '22 at 08:49
  • @FObersteiner: the code I wrote it copied directly from Python documentation. Before that there where the package `pytz` to handle timezones. With hacks in 2 months you will not known which variable is aware and which it naive, and so more problems. It is really better to take some more time and fix things. – Giacomo Catenazzi Dec 01 '22 at 09:06

2 Answers2

2

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(datetime.timezone.utc)
print(now)

Output

#2022-12-01 10:07:06.552326+00:00

Example 2 (Hack)

import datetime
now = datetime.datetime.now(datetime.timezone.utc)
now = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4]  + 'Z'
print(now)

Output

#2022-12-01T10:06:41.122Z

Hope this helps. Happy Coding :)

Amysoj-Louis
  • 635
  • 1
  • 1
  • 8
0

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")}')
Ftagliacarne
  • 675
  • 8
  • 16