Splitting timestamp column into separate date and time columns

后端 未结 7 781
执念已碎
执念已碎 2020-11-27 06:29

I have a pandas dataframe with over 1000 timestamps (below) that I would like to loop through:

2016-02-22 14:59:44.561776

I\'m having a har

7条回答
  •  猫巷女王i
    2020-11-27 06:54

    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
    

    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?

    For more details:

    https://docs.python.org/2/library/datetime.html

    How to make an unaware datetime timezone aware in python

    EDIT

    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)
    

提交回复
热议问题