【问题标题】:convert pandas datetime column yyyy-mm-dd to YYYYMMDD将熊猫日期时间列 yyyy-mm-dd 转换为 YYYYMMDD
【发布时间】:2018-03-31 18:39:01
【问题描述】:

我有一个日期时间列,格式为 yyyy-mm-dd。

我希望它采用整数格式 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,但也没有用。

【问题讨论】:

  • 你试过了吗:dates.dt.strftime('%Y%m%d')
  • 您确定该列包含datetime 值而不是看起来像datetimes 的strings?
  • 你试过了吗:df.dates.apply(lambda x: x.replace("-", "")) 因为看起来数据是字符串格式的。

标签: python pandas datetime


【解决方案1】:

如果您的列是字符串,则需要先使用 `pd.to_datetime',

df['Date'] = pd.to_datetime(df['Date'])

然后,将.dt 日期时间访问器与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

【讨论】:

  • 您也可以将df['Date'].astype(str).str.replace('-','').astype(int)df['Date'].astype(str).str.split('-').str.join('').astype(int)添加到您的选项中。
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 2011-04-09
  • 2013-10-19
  • 2022-11-10
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多