0

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?

ubh
  • 607
  • 1
  • 10
  • 15

3 Answers3

2

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

This is not an explanation of the error (see Padraic Cunningham's answer for that) but rather a shorter way of achieving your ultimate aim.

You appear to be converting compare_date to a time tuple. This is a direct way of doing it in pandas:

import pandas as pd
compare_date = pd.datetime.today()+pd.DateOffset(days=-60)
print compare_date.timetuple()

Resulting in:

time.struct_time(tm_year=2015, tm_mon=2, tm_mday=1, tm_hour=1, 
                 tm_min=20, tm_sec=43, tm_wday=6, tm_yday=32, tm_isdst=-1)
daedalus
  • 10,873
  • 5
  • 50
  • 71
0

See the explanation of mktime() error in @Padraic Cunningham's answer.

  1. pandas.datetime is datetime.datetime. You should use it directly:

    from datetime import datetime, timedelta
    
    compare_date = datetime.utcnow() - timedelta(60)
    posix_timestamp = (compare_date - datetime(1970, 1, 1)).total_seconds()
    

    See Converting datetime.date to UTC timestamp in Python

    If you compare_date is not in UTC then you should convert it to UTC first. See Find if 24 hrs have passed between datetimes - Python -- note: mktime() may fail!

  2. To get the timestamp (epoch time) more directly, you could use time.time():

    import time
    
    timestamp = time.time() - 60 * 86400 # 60 days ago
    

Both solutions ignore leap seconds (unless "right" timezone is used in the 2nd one).

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670