将时间戳列拆分为单独的日期和时间列 [英] Splitting timestamp column into separate date and time columns
问题描述
我有一个熊猫数据框,上面有超过1000个时间戳(以下),我想循环遍历:
I have a pandas dataframe with over 1000 timestamps (below) that I would like to loop through:
2016-02-22 14:59:44.561776
我很难将这个时间戳分为日期"和时间"两列.日期格式可以保持不变,但是时间必须转换为CST(包括毫秒).
I'm having a hard time splitting this time stamp into 2 columns- 'date' and 'time'. The date format can stay the same, but the time needs to be converted to CST (including milliseconds).
感谢您的帮助
推荐答案
我不确定为什么首先要这样做,但是如果确实需要...
I'm not sure why you would want to do this in the first place, but if you really must...
df = pd.DataFrame({'my_timestamp': pd.date_range('2016-1-1 15:00', periods=5)})
>>> df
my_timestamp
0 2016-01-01 15:00:00
1 2016-01-02 15:00:00
2 2016-01-03 15:00:00
3 2016-01-04 15:00:00
4 2016-01-05 15:00:00
df['new_date'] = [d.date() for d in df['my_timestamp']]
df['new_time'] = [d.time() for d in df['my_timestamp']]
>>> df
my_timestamp new_date new_time
0 2016-01-01 15:00:00 2016-01-01 15:00:00
1 2016-01-02 15:00:00 2016-01-02 15:00:00
2 2016-01-03 15:00:00 2016-01-03 15:00:00
3 2016-01-04 15:00:00 2016-01-04 15:00:00
4 2016-01-05 15:00:00 2016-01-05 15:00:00
向CST的转换比较棘手.我假设当前时间戳是不知道的",即它们没有附加时区?如果没有,您将如何转换它们?
The conversion to CST is more tricky. I assume that the current timestamps are 'unaware', i.e. they do not have a timezone attached? If not, how would you expect to convert them?
有关更多详细信息:
https://docs.python.org/2/library/datetime.html
编辑
另一种方法,该方法仅跨时间戳循环一次,而不是两次:
An alternative method that only loops once across the timestamps instead of twice:
new_dates, new_times = zip(*[(d.date(), d.time()) for d in df['my_timestamp']])
df = df.assign(new_date=new_dates, new_time=new_times)
这篇关于将时间戳列拆分为单独的日期和时间列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!