Vic13
Vic13

Reputation: 561

Standard date and time frame in python

I am using the below code to convert str(' 1495596971') to '%Y-%m-%d %H:%M:%S' but unable to do it for the whole column. Could you please help me with that?

ho['tweet'] = ho['tweet'].astype(str)
c=ho['tweet']
stddate=c.split('.')[0].split('0')[1]


t=print(
    datetime.datetime.fromtimestamp(
       int(stddate)
    ).strftime('%Y-%m-%d %H:%M:%S')
)

It is showing this error:-'Series' object has no attribute 'split'

Input:-

              tweet
0     1495596971.6034188::automotive auto ebc greens...
1     1495596972.330948::new free stock photo of cit...
2     1495596972.775966::ebay: 1974 volkswagen beetl...
3     1495596975.6460807::cars fly off a hidden spee...
4     1495596978.12868::rt @jiikae: guys i think mar...

I only want '1495596971','1495596972',etc this data from the column and want to convert it to standard date and time format.

Upvotes: 2

Views: 1518

Answers (2)

Tiny.D
Tiny.D

Reputation: 6556

Pandas Series has no method split, what you can do is get every item, then split with '.', then fetch str ('1495596971'), convert and format it :

import pandas as pd
import datetime
c =  pd.Series(['1495596971.6034188::automotive auto ebc greens','1495596972.330948::new free stock photo of cit','1495596972.775966::ebay: 1974 volkswagen beetl'])
stddate_list = [c[i].split('.')[0] for i in range(len(c))]
print(stddate_list)
t = [datetime.datetime.fromtimestamp(int(stddate)).strftime('%Y-%m-%d %H:%M:%S') for stddate in stddate_list]
print(t)

Output for stddate_list and t:

['1495596971', '1495596972', '1495596972']
['2017-05-24 11:36:11', '2017-05-24 11:36:12', '2017-05-24 11:36:12']

Upvotes: 2

Eliethesaiyan
Eliethesaiyan

Reputation: 2322

You can use apply option on Series object to act on each record in the serie as column

ho['tweet'] = ho['tweet'].astype(str)
c=ho['tweet']
stddate=c.apply(lambda x:x.split('.')[0])

Upvotes: 0

Related Questions