0
votes

The time in Asia/Kolkata time zone is 8/8/20, 8:00 (%m/%d/%y, %H:%M format). I first converted the datetime to UTC timezone and then changed to milliseconds. I compared the results to online (https://www.epochconverter.com/), there is some difference in the value.

Asia/Kolkata Timezone datetime (input): 8/8/20, 8:00
UTC Timezone datetime: 8/8/20, 2:30
calculated value of milliseconds since Epoch: 1596873600000
actual value of milliseconds since Epoch: 1596853800000

Python Script:

my_time = datetime.strptime(timerangestart, '%m/%d/%y, %H:%M')
timestart = my_time.replace(tzinfo=timezone.utc).timestamp()
timestart = timestart * 1000

what is it that I am doing wrong? Can I get some help on this?

2

2 Answers

1
votes

if you replace tzinfo with timezone.utc, Python will assume 8/8/20, 8:00 is UTC. What you want is astimezone(). If you don't pass a time zone, it will automatically use your machine's local time [docs].

from datetime import datetime, timezone
timerangestart = '8/8/20, 8:00'

# parse the string and localize to your time zone (OS setting):
my_time = datetime.strptime(timerangestart, '%m/%d/%y, %H:%M').astimezone() 
ts_ms = my_time.timestamp() * 1000 # no need to convert to UTC; UNIX time (should) always refer to UTC

Notice that by default, Python will assume that datetime objects without a time zone (tzinfo=None) belong in local time - so you could even omit the .astimezone()! However, I'd prefer to set the time zone so that it is more clear what is happening.

If you want to check for another time zone, you could use dateutil and e.g. write

from dateutil.tz import gettz

my_time = datetime.strptime(timerangestart, '%m/%d/%y, %H:%M').replace(tzinfo=gettz('US/Eastern'))
ts_ms = my_time.timestamp() * 1000
0
votes

This is how I resolved it

timerangestart = '8/8/20, 8:00'
my_time = datetime.strptime(timerangestart, '%m/%d/%y, %H:%M')
timerangestart = pytz.timezone("Asia/Kolkata").localize(my_time).astimezone(pytz.timezone("UTC")) 
timestart = int(timerangestart.timestamp() * 1000)