Search code examples
pythondatetimetimepandasmktime

python time mktime throwing error


I am trying to convert a pandas datetime to an epoch using the code below.

import time
import pandas as pd

compare_date = pd.datetime.today()+pd.DateOffset(days=-60)
print time.mktime(datetime.datetime.strptime(compare_date, "%Y-%m-%d").timetuple())

It's throwing an error

'unicode' object has no attribute 'mktime'

I tried with this code as well

t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )
print secs

And, it's still throwing the same error. I am using Python version 2.7.5. What am I missing here?


Solution

  • You have somehow set time equal to a unicode object in your code, you also cannot pass a Timestamp to strptime it must be a string

    In [15]: time = u"foo"
    
    In [16]: time.mktime
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-16-b93f36374edc> in <module>()
    ----> 1 time.mktime
    
    AttributeError: 'unicode' object has no attribute 'mktime'
    

    You need to go through your code and see where you have references to time, somewhere you have time = some_unicode_object

    Not exactly sure what you want at the end but using strftime on the TimeStamp object will be closer:

    print time.mktime(datetime.datetime.strptime(compare_date.strftime("%Y-%m-%d"), "%Y-%m-%d").timetuple())
    
    1422748800.0