0

I am trying to get the corresponding Epoch Unix timestamp (in seconds) for the following New York date and time:

2020-09-25 09:30 New York Time.

Which according to https://www.epochconverter.com/timezones?q=1601040600&tz=America%2FNew_York correponds to:

Conversion results (1601040600)
1601040600 converts to Friday September 25, 2020 09:30:00 (am) in time zone America/New York (EDT)

This is what I have tried:

import datetime
import pytz
​
et = pytz.timezone('America/New_York')
​
mydt = datetime.datetime(2020,9,25,9,30,0,0,et)

​myepoch = int(mydt.timestamp())
​
print('2020-09-25 09:30 ET Epoch: ', myepoch)
​    ​
>>> OUTPUT
2020-09-25 09:30 ET Epoch:  1601043960
​

So it gives 1601043960 instead of 1601040600. Why and what shall be done to get the right value?

Note the solution shall work for any date, so it must automatically take care of EST/EDT daylight saving.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • if you have access to a geographic database (e.g. OSM/Nominatim), you could even look up the coordinates of the city with [geopy](https://geopy.readthedocs.io/en/stable/), get the time zone for that coordinates using [timezonefinder](https://github.com/MrMinimal64/timezonefinder) and *then* obtain the local time. – FObersteiner Oct 26 '20 at 07:38

1 Answers1

0

It seems the solution is this one:

import datetime
import pytz
​
et = pytz.timezone('America/New_York')
​
mydt = et.localize(datetime.datetime(2020,9,25,9,30,0,0))

​myepoch = int(mydt.timestamp())
​
print('2020-09-25 09:30 ET Epoch: ', myepoch)
​    ​
>>> OUTPUT
2020-09-25 09:30 ET Epoch:  1601040600
M.E.
  • 4,955
  • 4
  • 49
  • 128
  • 1
    see [deprecation of pytz](https://pypi.org/project/pytz-deprecation-shim/) and [Display the time in a different time zone](https://stackoverflow.com/a/63628816/10197418) – FObersteiner Oct 21 '20 at 06:41
  • 1
    oh and check out [the fastest footgun in the west](https://blog.ganssle.io/articles/2018/03/pytz-fastest-footgun.html) as to *why* you get invalid timestamps if you don't localize (LMT...) ;-) – FObersteiner Oct 21 '20 at 08:33