Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting datetime to POSIX time

How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.

like image 416
Jason Baker Avatar asked Oct 31 '08 21:10

Jason Baker


People also ask

Is POSIX time always UTC?

Posix time is almost based on UTC, but doesn't include leap seconds that get thrown in at unpredictable (at least to me) intervals every few years.

How do I convert datetime to epoch time in Python?

Using strftime() to convert Python datetime to epoch strftime() is used to convert string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime().

What is Posix timestamp Python?

A UNIX time or Epoch or POSIX time is the number of seconds since the Epoch. Unix time (also known as Epoch time, POSIX time, seconds since the Epoch, or UNIX Epoch time) describes a point in time. It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds.

How do you convert datetime to seconds since epoch?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.


2 Answers

import time, datetime  d = datetime.datetime.now() print time.mktime(d.timetuple()) 
like image 187
kender Avatar answered Sep 20 '22 15:09

kender


For UTC calculations, calendar.timegm is the inverse of time.gmtime.

import calendar, datetime d = datetime.datetime.utcnow() print calendar.timegm(d.timetuple()) 
like image 20
fixermark Avatar answered Sep 17 '22 15:09

fixermark