Convert python datetime to epoch with strftime

PythonDatetimeUtcEpochStrftime

Python Problem Overview


I have a time in UTC from which I want the number of seconds since epoch.

I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.

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

1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.

So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?

How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).

Python Solutions


Solution 1 - Python

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

>>> (datetime.datetime(2012,04,01,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'

Solution 2 - Python

I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

Solution 3 - Python

import time
from datetime import datetime
now = datetime.now()

time.mktime(now.timetuple())

Solution 4 - Python

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn't let me comment on existing answer)

Solution 5 - Python

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3

Solution 6 - Python

For an explicit timezone-independent solution, use the pytz library.

import datetime
import pytz

pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()

Output (float): 1333238400.0

Solution 7 - Python

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs... https://docs.python.org/2/library/time.html#module-time

Solution 8 - Python

In Python 3.7

> Return a datetime corresponding to a date_string in one of the formats > emitted by date.isoformat() and datetime.isoformat(). Specifically, > this function supports strings in the format(s) > YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * > can match any single character.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoelView Question on Stackoverflow
Solution 1 - PythonjleahyView Answer on Stackoverflow
Solution 2 - PythonBorrajaXView Answer on Stackoverflow
Solution 3 - PythonsrossrossView Answer on Stackoverflow
Solution 4 - PythonCharles PlagerView Answer on Stackoverflow
Solution 5 - PythonMarc MaxmeisterView Answer on Stackoverflow
Solution 6 - PythonMoobieView Answer on Stackoverflow
Solution 7 - PythonLuis PolloView Answer on Stackoverflow
Solution 8 - PythonSuperNovaView Answer on Stackoverflow