簡體   English   中英

在python pandas中,如何將此格式化的日期字符串轉換為datetime

[英]In python pandas, how can I convert this formatted date string to datetime

我已經嘗試了幾種使用to_datetime ,但到目前為止我只能將它作為“對象”返回to_datetime

pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),dayfirst=True)

該命令的返回值為:

0    28Dec2013 19:23:15
dtype: object

您可以將format參數傳遞給to_datetime函數。

>>> import pandas as pd
>>> df = pd.to_datetime(pd.Series(['28Dec2013 19:23:15']),format="%d%b%Y %H:%M:%S",dayfirst=True)
>>> df
0   2013-12-28 19:23:15
dtype: datetime64[ns]

如果您需要在數據框中轉換現有列,請使用輔助函數convapply方法。

import datetime
import pandas as pd

def conv(x):
    return datetime.datetime.strptime(x, '%d%b%Y %H:%M:%S')

series = pd.Series(['28Dec2013 19:23:15'])
converted = series.apply(conv)

0   2013-12-28 19:23:15
dtype: datetime64[ns]

熊貓不承認日期時間格式。

>>> pd.to_datetime(Series(['28Dec2013 19:23:15']))
0    28Dec2013 19:23:15
dtype: object
>>> pd.to_datetime(Series(['28 Dec 2013 19:23:15']))
0   2013-12-28 19:23:15
dtype: datetime64[ns]

您需要解析要輸入系列的字符串。 正則表達式可能是一個很好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM