[英]Python pandas date time, how to convert these dates to pandas datetime?
我的日期格式為“月,年”:
82013
102013
但我希望它們成為常規的熊貓約會時間。 當我將這些日期插入pd.datetime時,我得到
1970-01-01 00:00:00.000082013
這是非常錯誤的。
咨詢將不勝感激謝謝。
正如roganjosh所說,最好是先以一種更簡單的格式獲取日期。 但是,如果您對此感到困惑,則只需告訴pd.to_datetime您期望的格式就可以解決。
dates = pd.Series(['82013', '102013'])
pd.to_datetime(dates, format='%m%Y')
df
date
0 82013
1 102013
首先,使用str.extract
將月份和年份提取為單獨的列:
u = df.date.astype(str).str.extract(r'^(?P<month>\d{1,2})(?P<year>\d{4})$', expand=True)
month year
0 8 2013
1 10 2013
現在,讓pd.to_datetime
接管。
pd.to_datetime(u.assign(day=1))
0 2013-08-01
1 2013-10-01
dtype: datetime64[ns]
如果可能的值無效,請使用
pd.to_datetime(u.assign(day=1), errors='coerce')
使用Python的標准datetime
模塊:
Python 3.7.2 (default, Jan 16 2019, 19:49:22)
[GCC 8.2.1 20181215 (Red Hat 8.2.1-6)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.strptime('82013', '%m%Y')
datetime.datetime(2013, 8, 1, 0, 0)
>>> datetime.strptime('102013', '%m%Y')
datetime.datetime(2013, 10, 1, 0, 0)
>>>
以這種方式生成的日期將被設置為該月的第一天,零時零分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.