Python Forum

Full Version: How to get utcnow + 2 hours?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello ,
I have a running code the send to a client current_time
I have notice that it send him time in this way:

current_time=datetime.utcnow().isoformat())
I want to send it gmt +2

Thanks,
datetime.datetime.utcnow is a bad accident.
Someone introduced it without thinking about the consequences.
The bad thing with utcnow is, that it returns a datetime object with UTC0 but not timezoneinfo attached to this datetime object. So it's in the context of timezone aware use useless.

Quick-Fix: datetime.datetime.now(datetime.timezone.utc)
Getting GMT+2

import datetime


gmt2 = datetime.timezone(datetime.timedelta(hours=2), "GMT+2")
# the name "GMT+2" is optional, the name does not appear in output of isoformat, only the offset
now_gmt2 = datetime.datetime.now(gmt2)
print(now_gmt2.isoformat())
datetime.datetime.now() just reurn the local datetime without timezone information.
If you pass timezone datetime.datetime.now(tzinfo), then you can get the current time for the location/offset.


Extrainfo

Since Python 3.9 the module zoneinfo was introduced, which access the timezone database on the system. For windows is an additional first party package called tzinfo. (On Windows is not timezone database preinstalled)

import datetime
from zoneinfo import ZoneInfo


# with known location
moscow = ZoneInfo("Europe/Moscow")
print("ZoneInfo:", moscow)
now_in_moskow = datetime.datetime.now(moscow)
print("Timezone aware datetime:", now_in_moskow)

# no known location, but offset is known
print()
print("Offset 1")
positive_offset = datetime.timedelta(hours=2)
print("Positive offset:", positive_offset)

print("offset 2")
negative_offset = datetime.timedelta(hours=-2)
print("Negative offset:", negative_offset)

tz1 = datetime.timezone(positive_offset, "GMT+2")
tz2 = datetime.timezone(negative_offset, "GMT-2")

print("TimeZone 1:", tz1)
print("TimeZone 2:", tz2)

now1 = datetime.datetime.now(tz1)
now2 = datetime.datetime.now(tz2)

print(now1)
print(now2)
print(now2.astimezone(tz1))

# you can't mix naive datetime with timezone aware datetime
naive_datetime_no_zoneinfo = datetime.datetime.now()
try:
    naive_datetime_no_zoneinfo - now1
except TypeError as e:
    print("Got expected TypeError:", e.args[0])

print()
print("ISO8601")
print("Moscow:", now_in_moskow.isoformat())
print("now1:", now1.isoformat())
print()

print("Removing microseconds from moscow time")
print(now_in_moskow.replace(microsecond=0).isoformat())
thank you for the explain and example!