我有一个带有日期时间列的日期框架,格式为yyyy-mm-dd。
我想以intery格式yyyymmdd拥有它。我不断使用这个抛出错误
x=dates.apply(dt.datetime.strftime('%Y%m%d')).astype(int)
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
这在我尝试传递数组时不起作用。我知道,如果我只传递元素,它将转换,但是我该如何使用pythonic呢?我确实尝试过使用lambda,但这也不起作用。
最佳答案
如果您的栏位是字串,则需要先使用`pd.to_datetime',
df['Date'] = pd.to_datetime(df['Date'])
然后,将
.dt
datetime访问器与strftime
结合使用:df = pd.DataFrame({'Date':pd.date_range('2017-01-01', periods = 60, freq='D')})
df.Date.dt.strftime('%Y%m%d').astype(int)
或使用lambda函数:
df.Date.apply(lambda x: x.strftime('%Y%m%d')).astype(int)
输出:
0 20170101
1 20170102
2 20170103
3 20170104
4 20170105
5 20170106
6 20170107
7 20170108
8 20170109
9 20170110
10 20170111
11 20170112
12 20170113
13 20170114
14 20170115
15 20170116
16 20170117
17 20170118
18 20170119
19 20170120
20 20170121
21 20170122
22 20170123
23 20170124
24 20170125
25 20170126
26 20170127
27 20170128
28 20170129
29 20170130
30 20170131
31 20170201
32 20170202
33 20170203
34 20170204
35 20170205
36 20170206
37 20170207
38 20170208
39 20170209
40 20170210
41 20170211
42 20170212
43 20170213
44 20170214
45 20170215
46 20170216
47 20170217
48 20170218
49 20170219
50 20170220
51 20170221
52 20170222
53 20170223
54 20170224
55 20170225
56 20170226
57 20170227
58 20170228
59 20170301
Name: Date, dtype: int32
关于python - 将pandas datetime列yyyy-mm-dd转换为YYYYMMDD,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46834732/