Reputation:
I am using linux aws machine and there is a timezone difference when I do datetime.datetime.now. So I have tried this method to overcome the timezone error
format = "%Y-%m-%d %H:%M:%S %Z%z"
current_date = datetime.datetime.now()
now_asia = current_date.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))
when I do my window machine I didnt get any error. The same lines when I use in my linux machine I am getting "ValueError: astimezone() cannot be applied to a naive datetime"
To debug this I tried the methods which is mentioned in this link pytz and astimezone() cannot be applied to a naive datetime
when I tried the first answer I am not getting any error but the timezone is not converted. when I tried the second answer I am getting an error 'AttributeError: 'module' object has no attribute 'utcnow'
I tried this
>>>loc_date = local_tz.localize(current_date)
>>> loc_date
datetime.datetime(2020, 4, 6, 7, 23, 36, 702645, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
>>> loc_date.strftime(format)
'2020-04-06 07:23:36 IST+05:30'
I am getting this ,so according to indian time if we add 5:30 it will be correct. How should i do it.
Upvotes: 3
Views: 583
Reputation: 2426
Please check that you are indeed running the Python 3.7 interpreter in the cloud. Citing the documentation for the astimezone()
function:
Changed in version 3.6: The astimezone() method can now be called on naive instances that are presumed to represent system local time.
Indeed, I just tested the script using Python 3.5.9 and pytz
2019.3 and I get
File "timez.py", line 6, in <module>
now_asia = current_date.astimezone(timezone('Asia/Kolkata'))
ValueError: astimezone() cannot be applied to a naive datetime
But when using Python 3.7.6 on an Amazon Linux 2 AMI instance, the code runs correctly.
Nevertheless, I would suggest to use timezone-aware datetimes from the start.
In the code you're referencing, you're getting that there's no utcnow
attribute because that code imports from datetime import datetime
, while you're doing import datetime
. To make it work, you would use
now_utc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
But note that the Python documentation now suggests you to use the tz
parameter in datetime.now
:
import datetime
import pytz
now_utc = datetime.datetime.now(tz=pytz.utc)
local_tz = pytz.timezone('Asia/Kolkata')
now_asia = now_utc.astimezone(local_tz)
format = "%Y-%m-%d %H:%M:%S %Z%z"
print(now_asia.strftime(format))
which prints 2020-04-22 09:25:21 IST+0530
in my case.
Upvotes: 2