The following code line gives me the UTC timing on the production server.
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
Please suggest a way to convert above UTC timezone to IST(Indian Standard Time) timing.
Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).
datetime.now()
gives you a naive datetime object that represents local time according to the setting of the machine you run the script on (which in this case just happens to be UTC since it's a server). See the docs.
To get "now" in a specific timezone, you can set the tz
property appropriately.
Python >= 3.9: you have zoneinfo in the standard lib to do this:
from zoneinfo import ZoneInfo
dtobj = datetime.now(tz=ZoneInfo('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:11:43.594442+05:30
Python < 3.9: I'd recommend the dateutil package to do so (or use zoneinfo
via backports.zoneinfo).
from datetime import datetime
from dateutil.tz import gettz
dtobj = datetime.now(tz=gettz('Asia/Kolkata'))
print(dtobj)
>>> 2020-07-23 11:08:54.032651+05:30
from datetime import datetime
import pytz
tz_NY = pytz.timezone('Asia/Kolkata')
datetime_NY = datetime.now(tz_NY)
print("India time:", datetime_NY.strftime("%Y-%m-%d %H:%M:%S.%f"))
>>India time: 2021-05-03 12:25:21.877976
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With