I have the input as a Unix timestamp, which is generated according to UTC time. I need to convert it to human readable time and then adjust the time zones, which is 02:00.
Using the datetime library, I have tried:
from datetime import datetime
import pytz
time = "1657893300324"
logtime = datetime.utcfromtimestamp(int(time)/1000).isoformat(sep=',', timespec='milliseconds')
timezone = pytz.timezone('Europe/Berlin')
d_aware = timezone.localize(int(logtime))
print(d_aware)
error thrown in this process:
ValueError: invalid literal for int() with base 10: '2022-07-15,13:55:00.324'
Another method:
from datetime import datetime
from datetime import timedelta
time = "1657893300324"
logtime = datetime.utcfromtimestamp(int(time)/1000).isoformat(sep=',', timespec='milliseconds')
two_hrs = datetime.timedelta(hours=2)
local_time = logtime two_hrs
print(local_time)
error thrown:
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
CodePudding user response:
You can do this :
time = "1657893300324"
timeInSeconds = int(time[0:10])
#add the 2 hours in seconds
timeInSeconds = 3600*2 #there is 3600 seconds in one hour
#and the convert it to a datetime object in python
date = datetime.datetime.fromtimestamp(timeInSeconds)
#and print it readable
print(date.isoformat())
#or even better :
s = str(date.month) "-" str(date.day) "-" str(date.year) " at " str(date.hour) ":" str(date.minute)
Hope it helps ! :)
CodePudding user response:
convert the Unix timestamp to UTC datetime, then change the timezone using astimezone
.
from datetime import datetime, timezone
import pytz
tz = pytz.timezone('Europe/Berlin')
t = "1657893300324"
logtime = datetime.fromtimestamp(int(t)/1000, timezone.utc)
d_aware = logtime.astimezone(tz)
print(d_aware)
# 2022-07-15 15:55:00.324000 02:00
Note: pytz
is deprecated. Use Python 3.9's zoneinfo instead, example.