简体   繁体   English

将字符串正确转换为日期时间?

[英]Proper conversion of string to datetime?

I have data in the form of yyyymm in a CSV file, I want to import it into pandas and find the range of timeperiod.我在 CSV 文件中有 yyyymm 形式的数据,我想将其导入 pandas 并找到时间段范围。 eg: 202201. I want to apply datetime functions to this but am unable to convert it into appropriate format.例如:202201。我想对此应用datetime时间函数,但无法将其转换为适当的格式。

test['YEAR_MONTH'] = pd.to_datetime(
                            test['YEARMONTH'], format='%Y%m', errors='coerce').dropna()

I tried using this, but to no avail.我尝试使用它,但无济于事。

>>> import pandas as pd
>>> import datetime

# Sample data as per OP's format
>>> test = pd.DataFrame({'YEARMONTH':['202201','202202','202203']})
>>> test
   YEARMONTH
0  202201
1  202202
2  202203

# Using strptime to convert to datetime object
>>> test_mod = test['YEARMONTH'].apply(lambda x: datetime.datetime.strptime(x,'%Y%m'))
>>> test_mod
0   2022-01-01
1   2022-02-01
2   2022-03-01
Name: YEARMONTH, dtype: datetime64[ns]

# Note - By default it assigns date as the first date of every month

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM