Python - Datetime with Timezone to Epoch

python - datetime with timezone to epoch

NOTE: My answer is flat-out wrong. (I'd like to delete it, but am unable to do so until the accept flag is removed.)

Please see J.F.Sebastian's answer.

Here is code demonstrating a value of now_tz for which our two methods produce different results.

import calendar
import pytz
import datetime as dt

tz1 = pytz.timezone('US/Eastern')
utc = pytz.timezone('UTC')
now = utc.localize(dt.datetime(2002, 10, 28), is_dst=None)
now_tz = now.astimezone(tz1)
now_epoch = calendar.timegm(now_tz.utctimetuple())
begin_day = tz1.normalize(now_tz.replace(hour=0, minute=0, second=0))

midnight = tz1.localize(dt.datetime.combine(now_tz, dt.time(0, 0)), is_dst=None)
if begin_day != midnight:
print(begin_day)
# 2002-10-27 01:00:00-04:00 # my result -- is not midnight
print(midnight)
# 2002-10-27 00:00:00-04:00 # J.F.Sebastian's result is correct

(Original answer redacted)

Convert datetime object in a particular timezone to epoch seconds in that timezone

Your datetime is not a naive datetime, it knows about the timezone it's in (your print states that is -5). So you just need to set it as utc before you convert it to epoch

>>> import time, pytz
>>> utc = pytz.timezone('UTC')
>>> utc_dt = utc.normalize(dt.astimezone(utc))
>>> time.mktime(utc_dt.timetuple())
1355270789.0 # This is just to show the format it outputs

If the dt object was a naive datetime object, you'd need to work with time zones to comply to daylight saving time while finding the correct hours between GMT 0. For example, Romania in the winter, it has +2 and in the summer +3.

For your -5 example, New-York will do:

>>> import time,pytz
>>> timezone = pytz.timezone('America/New_York')
>>> local_dt = timezone.localize(dt)

Now you have a non-naive datetime and you can get the epoch time like I first explained.
Have fun

Convert python datetime to epoch with strftime

If you want to convert a python datetime to seconds since epoch you could do it explicitly:

>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

Why you should not use datetime.strftime('%s')

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

Python: Get datetime (with timezone info) from number (epoch time) and convert it to string of specific date format

The time that you are having is the UNIX time (also known as Epoch or POSIX time). You can convert it into the datetime object and then format it as:

>>> from datetime import datetime

>>> my_datetime = datetime.fromtimestamp(1508486400)
>>> my_datetime.strftime('%d/%m/%Y')
'20/10/2017'

Edit: Based on desired time you mentioned, looks like you expect the time to be in "CAT+2:00:00" timezone. In order to do that, you may use pytz module with timezone "Africa/Harare" as:

>>> from datetime import datetime
>>> import pytz

>>> my_datetime = datetime.fromtimestamp(1508486400, tz= pytz.timezone('Africa/Harare'))
# Will hold the date time object as:
# datetime.datetime(2017, 10, 20, 10, 0, tzinfo=<DstTzInfo 'Africa/Harare' CAT+2:00:00 STD>)

>>> my_datetime.strftime('%d/%m/%Y')
'20/10/2017'

You can get the list of all timezones using pytz.all_timezones.

Also take a look at List of tz database time zones wiki.

Convert datetime string, timezone to epoch seconds

you can use datetime timestamp to get the epoch time

from datetime import datetime
import pytz

def utc_seconds(str_dt, timezone):
timezone = pytz.timezone(timezone)
dt = datetime.strptime(str_dt, '%Y-%m-%d %H:%M:%S')
dt_timezone = timezone.localize(dt)

return int(dt_timezone.timestamp())

utc_seconds('2018-02-11 00:00:00', 'Asia/Singapore')
# 1518278400

Converting epoch time to a date in time zone in python

1565475300 this is 2019-08-10 22:15:00 in UTC

datetime.fromtimestamp(1565475300, tz=timezone.utc)
datetime.datetime(2019, 8, 10, 22, 15, tzinfo=datetime.timezone.utc)

so it is 23:15 in London time zone



Related Topics



Leave a reply



Submit