gpt4 book ai didi

python - Pd 系列日期时间以格式转换为日期时间

转载 作者:行者123 更新时间:2023-12-04 22:13:56 25 4
gpt4 key购买 nike

我在一列中有一系列日期和时间数据,无法弄清楚如何以给定的格式将时间戳更改为日期时间(从 %Y/%m/%d %H:%M:$S.%f 到 %Y/%m/%d %H:%M),我在下面显示的是我的工作表、代码、结果和我的尝试。
这是数据
enter image description here
我有这个

dataset_train =  pd.read_excel('2btc_usdt.xlsx',sheet_name=0)
datelist_train = list(dataset_train['datetime'])
print(datelist_train)
结果
[Timestamp('2017-08-17 13:00:00'), Timestamp('2017-08-17 14:00:00'),
Timestamp('2017-08-17 15:00:00.005000'), Timestamp('2017-08-17 16:00:00.010000'), Timestamp('2017-08-17 17:00:00.015000'), Timestamp('2017-08-17 18:00:00.020000'),
Timestamp('2017-08-17 19:00:00.025000'), Timestamp('2017-08-17 20:00:00.030000'), Timestamp('2017-08-17 21:00:00.035000'), Timestamp('2017-08-17 22:00:00.040000'), Timestamp('2017-08-17 23:00:00.045000'), Timestamp('2017-08-18 00:00:00.050000'),
Timestamp('2017-08-18 01:00:00.055000'), Timestamp('2017-08-18 02:00:00.060000'), Timestamp('2017-08-18 03:00:00.065000'), Timestamp('2017-08-18 04:00:00.070000'), Timestamp('2017-08-18 05:00:00.075000'), Timestamp('2017-08-18 06:00:00.080000'), Timestamp('2017-08-18 07:00:00.085000'), Timestamp('2017-08-18 08:00:00.090000'),
Timestamp('2017-08-18 09:00:00.095000'), Timestamp('2017-08-18 10:00:00.100000'), Timestamp('2017-08-18 11:00:00.105000'), Timestamp('2017-08-18 12:00:00.110000'), Timestamp('2017-08-18 13:00:00.115000'), Timestamp('2017-08-18 14:00:00.120000'),
Timestamp('2017-08-18 15:00:00.125000'), Timestamp('2017-08-18 16:00:00.130000'), Timestamp('2017-08-18 17:00:00.135000'), Timestamp('2017-08-18 18:00:00.140000'), Timestamp('2017-08-18 19:00:00.145000'), Timestamp('2017-08-18 20:00:00.150000'),
Timestamp('2017-08-18 21:00:00.155000'), Timestamp('2017-08-18 22:00:00.16..............
我试过的
#Attempt no1

datelist_train = list(dataset_train['date'])
datelist_train = [dt.datetime.strptime( date, "%Y/%m/%d %H:%M").date() for date in datelist_train]
#it just convert list to series and not changing the format

#Attempt no2
datelist_train = list(dataset_train['datetime'])
datelist_train = pd.to_datetime(datelist_train,unit='ms')
#i get message: unit='ms' not valid with non-numerical val='2017-08-17 13:00:00'

最佳答案

尝试了您的问题,下面的代码解决了它:

dataset_train = pd.read_excel(r'C:\Users\Downloads\Book 1.xlsx', sheet_name=0 )
print((dataset_train['timestamp']))
dataset_train['DATE'] = dataset_train['timestamp'].apply(lambda x: x.strftime('%Y/%m/%d %H:%M'))
print(dataset_train['DATE'])

关于python - Pd 系列日期时间以格式转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71194025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com