我在pandas中有一个date列,如下所示作为字符串数据类型:
df['Date]
Dec/2018
Mar/2017
Sep/2019
我希望熊猫中的日期列如下所示,datetime datatype
,
not string datatype
:
df['Date]
`December-2018`
`March-2017`
`September-2019`
答案 0 :(得分:1)
from datetime import datetime
import pandas as pd
# define sample data to create a dataframe from
data = {'Date': ['Dec/2018', 'Mar/2017', 'Sep/2019']}
df = pd.DataFrame(data)
# define a function to convert dates
def format_date(el):
return datetime.strptime(el, '%b/%Y').strftime('%B-%Y')
# apply conversion to desired column and store output in new column
df['Date_formatted'] = df['Date'].apply(format_date)
# print the dataframe to check result
print(df)
将以如下方式输出数据帧:
Date Date_formatted
0 Dec/2018 December-2018
1 Mar/2017 March-2017
2 Sep/2019 September-2019
答案 1 :(得分:1)
使用pd.to_datetime
的pandas
方法:
df['Date'] = pd.to_datetime(df['Date'], format='%b/%Y').dt.strftime('%B-%Y')
0 December-2018
1 March-2017
2 September-2019
Name: Date, dtype: object
答案 2 :(得分:0)
import datetime
x = datetime.date.today()
print(x.strftime("%B - %Y "))
有关其他信息,您可以阅读this。
我希望它会对您有所帮助。