Proper conversion of string to datetime?

Viewed 40

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. eg: 202201. I want to apply datetime functions to this but am unable to convert it into appropriate format.

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

I tried using this, but to no avail.

1 Answers
>>> 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

Related