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.


Asked by: Melissa155 | Posted: 06-10-2021






Answer 1

import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())

Answered by: Arthur317 | Posted: 07-11-2021



Answer 2

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

import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())

Answered by: Michelle967 | Posted: 07-11-2021



Answer 3

Note that Python now (3.5.2) includes a built-in method for this in datetime objects:

>>> import datetime
>>> now = datetime.datetime(2020, 11, 18, 18, 52, 47, 874766)
>>> now.timestamp() # Local time
1605743567.874766
>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC
1605725567.874766 # 5 hours delta (I'm in UTC-5)

Answered by: Audrey632 | Posted: 07-11-2021



Answer 4

In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.

import time, datetime

posix_now = time.time()

d = datetime.datetime.fromtimestamp(posix_now)
no_microseconds_time = time.mktime(d.timetuple())
has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001

print posix_now
print no_microseconds_time
print has_microseconds_time

Answered by: Rafael873 | Posted: 07-11-2021



Answer 5

Best conversion from posix/epoch to datetime timestamp and the reverse:

this_time = datetime.datetime.utcnow() # datetime.datetime type
epoch_time = this_time.timestamp()      # posix time or epoch time
this_time = datetime.datetime.fromtimestamp(epoch_time)

Answered by: Lydia514 | Posted: 07-11-2021



Answer 6

It depends

Is your datetime object timezone aware or naive?

Timezone Aware

If it is aware it's simple

from datetime import datetime, timezone
aware_date = datetime.now(tz=timezone.utc)
posix_timestamp = aware_date.timestamp()

as date.timestamp() gives you "POSIX timestamp"

NOTE: more accurate to call it an epoch/unix timestamp as it may not be POSIX compliant

Timezone Naive

If it's not timezone aware (naive), then you'd need to know what timezone it was originally in so we can use replace() to convert it into a timezone aware date object. Let's assume that you've stored/retrieved it as UTC Naive. Here we create one, as an example:

from datetime import datetime, timezone
naive_date = datetime.utcnow()  # this date is naive, but is UTC based
aware_date = naive_date.replace(tzinfo=timezone.utc)  # this date is no longer naive

# now we do as we did with the last one

posix_timestamp = aware_date.timestamp()

It's always better to get to a timezone aware date as soon as you can to prevent issues that can arise with naive dates (as Python will often assume they are local times and can mess you up)

NOTE: also be careful with your understanding of the epoch as it is platform dependent

Answered by: Anna761 | Posted: 07-11-2021



Similar questions

datetime - Converting Python String to Date

I need to convert the Python string "Mon Aug 29 2011 18:30:00 GMT+0530 (IST)" into "20110829T183000Z" and "20110829T173000Z" (Date + 1 hour). Never have been good at remembering datetime APIs, would appreciate the help here!


python - Converting utc time string to datetime object

I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error: (Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ') *** error: redefinition of group name 'M' as group 5; was group 2 Also, as this format is supposed to be quite a standard format isn't there a function availabl...


Python converting "March 2 2012" into a datetime object

When I call the following function, I get a struct_time obj. Is there a way to convert this into a date obj? import time date = time.strptime("March 2 2012", '%B %d %Y') Thanks


python - Converting a string to a datetime

I've got a python string like this "2012/04/08 13:31:00 UTC" How can I convert it to a datetime object?


python - Getting a datetime in this format and converting to 4 byte hex

I have a date time in this format. 1999-12-31 09:00:00 Which came from the hex value: F0C46C38 How do you make the datetime value of the above format into a 4 byte hex? The values I posted above are complements to each other. The hex in the second code block is reversed. Thank you!


datetime - Converting GMT to EST from CSV file using Python

I have a CSV file that has a date column and a time column. The time column is in GMT (24hr format) and I need to convert it to EST. Because it is daylight saving time, the time differential now is -5 hours here on the east coast. I need a way to read the CSV file and subtract 5 hours from all of the times in the column. My biggest problem is that many of the conversions would cover two days. For example, "Thu Nov 7,0...


python - Converting string to datetime object

I was trying to convert a string to a datetime object. The string I got from a news feed is in the following format: "Thu, 16 Oct 2014 01:16:17 EDT" I tried using datetime.strptime() to convert it. i.e., datetime.strptime('Thu, 16 Oct 2014 01:16:17 EDT','%a, %d %b %Y %H:%M:%S %Z') And got the following error: Traceback (most recent call last):  &...


python - Converting a datetime column to a string column

I'm trying to convert a datetime column back to a string in Pandas dataframe. the syntax I have so far is: all_data['Order Day new'] = dt.date.strftime(all_data['Order Day new'], '%d/%m/%Y') but this returns the error: descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'. Can anyone tell me where I'm going wrong.


python - converting a datetime object

I have an excel sheet which contains date. With the following I convert them to datetime objects: def excel_time_to_string(xltimeinput): try: retVal = xlrd.xldate.xldate_as_datetime(xltimeinput, wb.datemode) except ValueError: print('You passed in an argument in that can not be translated to a datetime.') print('Will return original value and carry...


python - Converting string to Numpy datetime

I'm using numpy 1.8.2 and the following code results in the error below: import numpy as np data = [] data.append(['2015-01-03 05:00:00', 5, 5.01]) data.append(['2015-01-04 05:00:00', 7, 7.01]) data.append(['2015-01-05 05:00:00', 8, 8.01]) data.append(['2015-01-06 05:00:00', 10, 10.01]) dt = np.dtype('M8', '<f8', '<f8') np.array(data, dtype=dt) produces the following output: ...


Converting python string to datetime obj with AM/PM

easy problem but this is bugging me: Say I have a string like this: test = '2015-08-12 13:07:32' To convert it into a datetime object and change it to AM/PM specification, shouldn't this work? datetime.datetime.strptime(test, '%Y-%m-%d %I:%M:%S %p') I'm getting an error like this: ValueError: time data '2015-08-12 13:07:32' does not match for...


python - Converting UTC datetime to PST in Django

I have a model which is the following: class Status(models.Model): capacity = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) active = models.DateTimeField(default=None) Given my model and my settings.py which has TIME_ZONE = 'UTC'. My goal is to display my times as 'US/Pacific' on my front-end. This unfortunately is not working ...


python - Converting year and day of year into datetime index in pandas

I have a dataframe: year doy 2000 49 2000 65 2000 81 2001 97 2001 113 2001 129 2001 145 2001 161 I want to create a datetime index for this dataframe. Here is what I am doing: df.index = pandas.DatetimeIndex(df['doy'].apply(lambda x: date(2000, 1, 1)+ relativedelta(days=int(x)-1))) However, this creates a datetim...


python - 1 hour off when converting RFC 2822 date to datetime

Here's what I'm trying to do: >>> from email.utils import parsedate >>> tup = parsedate("Fri, 22 Jan 2016 10:15:00 GMT") >>> tup (2016, 1, 22, 10, 15, 0, 0, 1, -1) >>> import datetime >>> import time >>> timestamp = time.mktime(tup) >>> timestamp 1453454100.0 >>> datetime.datetime.utcfromtimestamp(timestamp) datetime.datetime(2016, 1, 2...


python - Converting string with UTC offset to a datetime object

This question already has answers here:


python - Pandas error converting string to datetime

I'm trying to convert a string dataframe column to dates in pandas. However, I'm getting this error. I'm guessing the time zone is looking for EST, not ET. Is there a way to fix this? ValueError: time data '07/15/2004 / 04:50PM ET' does not match format '%m/%d/%Y / %I:%M%p %Z' (match) Thanks Edit: I did df['date'] = df['date'].str.replace('ET', 'EST') and it's still ...


python - Converting Tuple Index to a Datetime index

I am averaging my data frame by month/day/year etc and have run into trouble with my index being converted from Datetime to Tuple. I want to have my index in Datetime so that I can export it to excel for other non-python users and have it still make sense with timestamps. This what my Df look like: Index Date Time Value 1 1/26/2016 07:00 100000.0 2 1/26/2016 07:00 1000000.0 ...


Converting Epoch DateTime to Byte Array in Python

I am trying to convert epoch datetime to byte array in python but it is coming as 10 Byte, it should come in 4 Byte. from time import time curTime = int(time.time()) b = bytearray(str(curTime)) len(b) #comming as 10 Can any one help where i am wrong


datetime - Converting python time stamp to day of year

How can I convert a python timestamp into day of year: Timestamp('2015-06-01 00:00:00') I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)


python - Converting a csv file to Datetime

I've searched thoroughly for an answer before asking, but all I've been able to find was how to convert one column of my csv file into a datetime object. My problem is, my file has a separate column for year, month, day, hour, minute, and I've been struggling for a while to convert and combine them. Any help would be much appreciated. head of file content:


datetime - How to specify time zone (UTC) when converting to Unix time? (Python)

I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session: In [9]: mydate Out[9]: '2009-07-17T01:21:00.000Z' In [10]: parseddate = iso8601.parse_date(mydate) In [14]: ti = time.mktime(parseddate.timetuple()) In [25]: datetime.datetime.utcfromtimestamp(ti) Out[25]: datetime.datetime(2009, 7, 17, 7, 21) In [26]: datetime.datetime.fromtimestamp(ti) Out[2...


Converting a string to datetime in python

This question already has answers here:


datetime - Converting Python String to Date

I need to convert the Python string "Mon Aug 29 2011 18:30:00 GMT+0530 (IST)" into "20110829T183000Z" and "20110829T173000Z" (Date + 1 hour). Never have been good at remembering datetime APIs, would appreciate the help here!


Converting string to datetime object in Python (GAE)?

I'm very new to Python, but I need to migrate a project from PHP to Python (running in GAE environment) and I need to move all data from one database to GAE's one. The chellenge is to write data strings into datetime objects. Dates are stored as strings, which where created using PHP's pattern "l dS of F Y ( h:i:s A )" So every date looks like this: Sunday 31st of July 2005 ( 02:05:50 PM ) I've looked into Pyth...


Converting a String into a datetime object in python

I have a string field like this.. 2011-09-04 23:44:30.801000 and now I need to convert it to a datetime object in python so that I can calculate the difference between two datetime objects.


python - Converting utc time string to datetime object

I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error: (Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ') *** error: redefinition of group name 'M' as group 5; was group 2 Also, as this format is supposed to be quite a standard format isn't there a function availabl...


Python converting "March 2 2012" into a datetime object

When I call the following function, I get a struct_time obj. Is there a way to convert this into a date obj? import time date = time.strptime("March 2 2012", '%B %d %Y') Thanks


Converting integer to datetime in Python


python - Converting a string to a datetime

I've got a python string like this "2012/04/08 13:31:00 UTC" How can I convert it to a datetime object?


python - Getting a datetime in this format and converting to 4 byte hex

I have a date time in this format. 1999-12-31 09:00:00 Which came from the hex value: F0C46C38 How do you make the datetime value of the above format into a 4 byte hex? The values I posted above are complements to each other. The hex in the second code block is reversed. Thank you!


Converting PDF to HTML with Python

This question already has answers here:


python - Library for converting a traceback to its exception?

Just a curiosity: is there an already-coded way to convert a printed traceback back to the exception that generated it? :) Or to a sys.exc_info-like structure?


python - Converting a string of 1's and 0's to a byte array

I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents. How can I do this in Python?


vb6 - Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?

I've discovered VB2Py, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?


python - Converting from mod_python to mod_wsgi

My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially FieldStorage and Session (and sometimes Cookie), and from a scan of


django - Converting to safe unicode in python

I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error. Incorrect string value: '\xEF\xBF\xBDs m...' My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion. s = unicode(content...


Oracle / Python Converting to string -> HEX (for RAW column) -> varchar2

I have a table with a RAW column for holding an encrypted string. I have the PL/SQL code for encrypting from plain text into this field. I wish to create a trigger containg the encryption code. I wish to 'misuse' the RAW field to pass the plain text into the trigger. (I can't modify the schema, for example to add another column for the plain text field) The client inserting the data is Pytho...


python - How can I check Hamming Weight without converting to binary?

How can I get the number of "1"s in the binary representation of a number without actually converting and counting ? e.g. def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 n /= 2 return c >>> number_of_ones(5) 2 >>> number_of_ones(4) 1 ...


python - Django: Converting an entire set of a Model's objects into a single dictionary

If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you. Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: class DictModel(models.Model): key = models.CharField(20) value = models.CharField(200) DictModel.objects.all().to_dict()


python - What is the difference between converting to hex on the client end and using rawtohex?

I have a table that's created like this: CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) Using Python and cx_Oracle, if I do this: value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self.connection.execute("SELECT b FROM bin_test")






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top