【问题标题】:converting object to datetime without time将对象转换为没有时间的日期时间
【发布时间】:2020-07-24 13:29:55
【问题描述】:

我的数据框如下所示:

         Date      Region     Data
   0   200201        A        8.8
   1   200201        B        14.3
                    ...     
1545   202005        C        7.3
1546   202005        D        131

我想在没有时间的情况下将日期列(数据类型:对象)转换为 DateTime 索引。 yyyymm 或 yyyymmdd 或 yyyy-mm-dd 所有这些都无所谓,只要我可以擦除时间部分。

我已经搜索了 stackoverflow 并尝试了这些代码

# (1) 
df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m", errors = "coerce", uts = False)
# (2)
df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m")
df["Date"] = df["Date"].dt.normalize()
# (3)
df["Date"] = pd.to_datetime(df["Date"], format = "%Y%m")
df["Date"] = df["Date"].dt.date

对于 (1) 和 (2),我得到 ["Date"] 的时间像 yyyy-mm-dd 00:00:00。

对于 (3),我确实将 ["Date"] 设为 yyyymm,但 dtype 是对象。

我无法使用日期范围,因为同一日期重复了一段时间。

有没有办法在python中将yyyymm[object]转换为yyyymmdd[datetime]?

提前致谢。

【问题讨论】:

  • 欢迎来到 SO!如果您将程序的输出作为文本插入问题而不是链接屏幕截图,通常会更好。欲了解更多信息,请查看how to ask page.
  • 在我的系统中,命令运行正常
  • @a.deshpande012 好的,感谢您的提示!
  • @bigbounty 我认为我的 spyder 程序有问题。谢谢!

标签: python pandas datetime


【解决方案1】:

这可能是您的 DataFrame 在编辑器中的显示方式的显示配置问题。以正确格式获取数据的最简单方法是:

df['Date'] = pd.to_datetime(df['Date'], format = '%Y%m')

以下是来自repl.it 的结果以及您的 DataFrame 和此代码。日期格式正确,没有时间组件,并且具有正确的 dtype。

        Date Region  Data
0 2002-01-01      A   8.8

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Date    1 non-null      datetime64[ns]
 1   Region  1 non-null      object        
 2   Data    1 non-null      float64       
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 152.0+ bytes

您还可以尝试一种更复杂的方式,从日期时间到日期字符串再返回到日期时间。

df['Date'] = pd.to_datetime(df['Date'], format = '%Y%m').dt.date
df['Date'] = df['Date'].astype('datetime64[ns]')

最终的显示和dtypes是一样的。

        Date Region  Data
0 2002-01-01      A   8.8

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Date    1 non-null      datetime64[ns]
 1   Region  1 non-null      object        
 2   Data    1 non-null      float64       
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 152.0+ bytes

【讨论】:

  • 谢谢,我认为我的 spyder 出了点问题。我在 colab 中尝试了相同的代码,它以 yyyy-mm-dd 格式显示。非常感谢您的帮助和很好的解释。我真的很感激。
【解决方案2】:

问题中的日期列的格式为 YYYYMM(但没有天数)。函数pd.to_datetime() 隐式地将日期设置为 1。

函数pd.Period() 将格式为YYYYMM 的日期转换为pandas 句点。请注意,df['Date'] 可以是字符串或 6 位整数。

df['Date'].apply(lambda x: pd.Period(x, freq='M'))

0    2002-01
1    2002-01
2    2020-05
3    2020-05
Name: Date, dtype: period[M]

【讨论】:

  • 感谢您的帮助!我真的很感激!
猜你喜欢
  • 2017-01-08
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 2018-03-10
  • 1970-01-01
  • 2022-01-26
  • 2023-04-09
相关资源
最近更新 更多