[英]Converting string (MM-DD) into datetime in python
I want to make a time-series analysis with python, but i can't convert the data into datetime because the data is still in string (MM-DD).我想用 python 进行时间序列分析,但我无法将数据转换为日期时间,因为数据仍在字符串(MM-DD)中。
Period Jan-10 Feb-10 Mar-10 Apr-10 etc期间 Jan-10 Feb-10 Mar-10 Apr-10 等
Is there any other way to convert this kind of data into datetime object?有没有其他方法可以将此类数据转换为日期时间 object?
There is no need to use the datetime
module.无需使用
datetime
模块。 Pandas can convert strings to date when reading the data from the csv file or you can use the to_datetime
method after the data is loaded. Pandas 可以在从 csv 文件中读取数据时将字符串转换为日期,也可以在加载数据后使用
to_datetime
方法。
import pandas as pd
df = pd.read_csv('file.csv', parse_dates=['date'], infer_datetime_format=True)
If you are using a non-standard format, then you will get better results if you specify a format string.如果您使用的是非标准格式,那么如果您指定格式字符串,您将获得更好的结果。 Here, it looks like the format string is '%b-%y', which is the abbreviated month name and the two-digit year without the century.
在这里,格式字符串看起来像是'%b-%y',它是缩写的月份名称和没有世纪的两位数年份。
import pandas as pd
df = pd.read_csv('file.csv')
df['date'] = pd.to_datetime(df['date'], format='%b-%y')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.