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.
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.
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().
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.
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.
import time, datetime d = datetime.datetime.now() print time.mktime(d.timetuple())
For UTC calculations, calendar.timegm
is the inverse of time.gmtime
.
import calendar, datetime d = datetime.datetime.utcnow() print calendar.timegm(d.timetuple())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With