简体   繁体   中英

How to add the date in a datetime object when only time is present in timestamp

I am working on some time series data and the timestamp only includes the time( HH:MM:SS ) , but I need to add the YY/MM/DD to the timestamp. I working with pandas dataframe.

I tried using pd.to_datetime(), but it enters the current date that I call it.

df_17c = pd.read_csv(file_17c,sep ='\t', header = None,names=['TimeStamp','x','y','z'],  usecols =[0,3,4,5])

df_17s = pd.read_csv(file_17s,sep ='\t', header = None,names = ['TimeStamp','x','y','z'],usecols =[0,1,2,3])

 TimeStamp      x    y  z
0  23:59:58  26799 -218  0
1  23:59:58  26797 -218  0
2  23:59:58  26795 -218  0
3  23:59:58  26793 -218  0
4  23:59:58  26792 -217  0


The "TimeStamp" column is a object type ( string). When I convert using .to_datetime() it yields datetime object with the current date.

df_17c["Date"]= pd.to_datetime(df_17c['TimeStamp'])

            TimeStamp      x    y  z
0 2019-06-26 23:59:58  26799 -218  0
1 2019-06-26 23:59:58  26797 -218  0
2 2019-06-26 23:59:58  26795 -218  0
3 2019-06-26 23:59:58  26793 -218  0
4 2019-06-26 23:59:58  26792 -217  0

This isn't probably the most efficient way, but it's simple (basically add the date to the front of the string)

date = '2017-01-09T'  # or whatever (note the T)
pd.to_datetime(df['TimeStamp'].apply(lambda s: date+s)) 

example

df = pd.DataFrame({'time': ['08:11:09', '17:09:34']})

#   time
# 0  08:11:09
# 1  17:09:34

date_func = '2017-01-09T{}'.format  # avoid the use of lambda + more efficient

df['datetime'] = pd.to_datetime(df['time'].apply(date_func))

output

       time            datetime
0  08:11:09   2017-01-09 08:11:09
1  17:09:34   2017-01-09 17:09:34

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM