[python] Convert python datetime to epoch with strftime

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).

This question is related to python datetime utc epoch strftime

The answer is


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

time.mktime(now.timetuple())

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


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


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

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


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)


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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to utc

Convert LocalDateTime to LocalDateTime in UTC How to set the timezone in Django? Java Convert GMT/UTC to Local time doesn't work as expected Should MySQL have its timezone set to UTC? How to Convert UTC Date To Local time Zone in MySql Select Query How to convert UTC timestamp to device local time in android Convert python datetime to epoch with strftime Convert Java Date to UTC String How do I get a UTC Timestamp in JavaScript? Converting datetime.date to UTC timestamp in Python

Examples related to epoch

How to extract epoch from LocalDate and LocalDateTime? converting epoch time with milliseconds to datetime PostgreSQL: how to convert from Unix epoch to date? How to convert a string Date to long millseconds How do I get the unix timestamp in C as an int? Convert python datetime to epoch with strftime How do I get epoch time in C#? Android Get Current timestamp? How can I convert a datetime object to milliseconds since epoch (unix time) in Python? Convert a date format in epoch

Examples related to strftime

How to change the datetime format in pandas What exactly does the T and Z mean in timestamp? Convert python datetime to epoch with strftime Using %f with strftime() in Python to get microseconds Converting unix timestamp string to readable date YYYY-MM-DD format date in shell script Python strftime - date without leading 0?