Search code examples
pythonpandasdataframedatetimeunix-timestamp

AttributeError: 'Series' object has no attribute 'timetuple'


I am trying to convert a pandas column DateTime (UTC) which seems like this df_1['MESS_DATUM'] = 202209250000 to unixtime. My code looks like this:

df_1['MESS_DATUM'] = calendar.timegm(df_1['MESS_DATUM'].timetuple())

print(datetime.utcfromtimestamp(df_1['MESS_DATUM']))

But I am getting this error "AttributeError: 'Series' object has no attribute 'timetuple'". I have used the below method as well but my time is in UTC which is why it is not giving me the right unix time I guess:

df_1['MESS_DATUM'] = pd.to_datetime(df_1['MESS_DATUM'])
(df_1['MESS_DATUM'] - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s') 
print(df_1['MESS_DATUM'])  #it gives me the following datetime in unix form
1970-01-01 00:03:22.209252150

I tried the above method for a single datetime string as shown below and it works but for the whole datetime column it gives me this value 1970-01-01 00:03:22.209252150

dates = pd.to_datetime(['2022-09-15 13:30:00'])
# calculate unix datetime
dates = (dates - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
print(dates) # Int64Index([1663248600], dtype='int64')

I tried this method as well which gives me again the wrong unixtime

df_1['MESS_DATUM'] = pd.DatetimeIndex ( df_1['MESS_DATUM'] ).astype ( np.int64 )/1000000
print(df_1['MESS_DATUM']) 
202.209252 # this is the unixtime I get

Any helpful solution will be highly appreciated.


Solution

  • You could convert the value using the datetime library;

    d = 202209250000
    import datetime 
    datetime.datetime.strptime(str(d),'%Y%m%d%H%M').timestamp()
    

    Converting the column can be done using using df.apply;

    df = pd.DataFrame({'MESS_DATUM': [202209250000,202209260000,202209270000]})
    df['MESS_DATUM'] = df['MESS_DATUM'].apply(lambda x: datetime.datetime.strptime(str(x),'%Y%m%d%H%M').timestamp())