Skip to content Skip to sidebar Skip to footer

Convert Utc Timezone To Ist Python

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 abov

Solution 1:

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-2311: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-2311:08:54.032651+05:30

Solution 2:

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-0312:25:21.877976

Post a Comment for "Convert Utc Timezone To Ist Python"