Home > Mobile >  Timezone: Is there a way to print GMT (grenwich meantime) with datetime in python?
Timezone: Is there a way to print GMT (grenwich meantime) with datetime in python?

Time:10-29

The code works fine so far. I just included it for reference.

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.utcnow()

print(dt_today)

print(dt_now)

print(dt_utcnow)

print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

I tried the obvious:

dt_gmt = datetime.datetime.gmt()

but that didn't work.

CodePudding user response:

Instead of datetime.utcnow(), try datetime.now(timezone.utc) as mentioned in this answer.

Example below:

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.now(datetime.timezone.utc)

print(dt_now)

print(dt_utcnow)
print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

Output:

2021-10-28 19:13:35.069610
2021-10-28 23:13:35.069610 00:00
2021-10-28 23:13:35.069610 UTC

Alternate approach, if you really want to include "GMT" instead:

print(dt_utcnow.isoformat().replace(" 00:00", " GMT"))

Prints: 2021-10-28T23:18:35.637448 GMT

CodePudding user response:

help(datetime) led to the datetime part of python's library which clarified that gmtime and strftime turned out to be what I was looking for:

from time import gmtime, strftime
import time

print("\nGMT: " time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.gmtime())) 
print("Local: " strftime("%a, %d %b %Y %I:%M:%S %p %Z\n"))
  • Related