简体   繁体   English

在 python 中将字符串 (MM-DD) 转换为日期时间

[英]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.

相关问题 将 MM-DD 添加到年份 Python - Add MM-DD to Year Python 如何将 numpy 日期时间转换为“MM-DD”格式 - How to convert numpy datetime into the format "MM-DD" 将 Python 中的 TimeFormat 'DD/MM/YY HH:MM AM' 从字符串转换为 Datetime 'DD/MM/YY HH:MM:SS' - Converting TimeFormat 'DD/MM/YY HH:MM AM' from String in Python to Datetime 'DD/MM/YY HH:MM:SS' Python日期字符串mm / dd / yyyy到datetime - Python date string mm/dd/yyyy to datetime 将日期时间数据的数据框列转换为 DD/MM/YYYY 字符串数据 - Converting dataframe column of datetime data to DD/MM/YYYY string data 在python中将字符串日期转换为DateTime,在python中字符串格式为YYYY-MM-DD Hr-Min-Sec - Converting String Date to DateTime in python where String format is YYYY-MM-DD Hr-Min-Sec in python 如何将 Python 中 mm-dd 日期格式的“1030”转换为 10-30? - How to convert “1030” to 10-30 in mm-dd date format in Python? 将长日期时间转换为日期 (dd/mm/yyyy) - Converting long datetime into date (dd/mm/yyyy) 如何将日期时间数据从“YYYY-MM-DD HR-MN-SEC”格式提取到“MM-DD HR-MN-SEC”格式? - How to extract Datetime data from 'YYYY-MM-DD HR-MN-SEC' format to 'MM-DD HR-MN-SEC'' format? Python-使用日期时间将日期字符串从YYYY-MM-DD转换为DD-MMM-YYYY? - Python - convert date string from YYYY-MM-DD to DD-MMM-YYYY using datetime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM