0

I have the column of dates called 'Activity_Period' in this format '200507' which means July 2005 and I want to convert it to datetime format of ('Y'-'m') in python.

I tried to use the datetime.strp however it shows that the input has to be a string and not a series.

df.Activity_Period=datetime.strptime(df.Activity_Period, '%Y-%m')

The following is the error I get

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-ac32eb324a0b> in <module>
----> 1 df.Activity_Period=datetime.strptime(df.Activity_Period, '%Y-%m')

TypeError: strptime() argument 1 must be str, not Series
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
Hassan
  • 1
  • 2
  • could you show us the code? (use ``` for formatting code blocks) – Anadactothe Aug 22 '19 at 16:23
  • Related: [Fastest way to parse a column to datetime in pandas](https://stackoverflow.com/q/50507468/190597), or [How to convert Period string to actual Period type](https://stackoverflow.com/q/40445076/190597). – unutbu Aug 22 '19 at 16:29

1 Answers1

1
 import datetime as dt
 import pandas as pd

 #simple example

 timestamp = '200507'
 result = dt.datetime.strptime(timestamp, '%Y%m')
 print(result)


 #Example using pandas series

 series = pd.Series(['200507', '200508', '200509', '200510'])
 series = pd.to_datetime(series, format='%Y%m')
 print(series)


 #for your DF
 df['Activity_Period'] = pd.to_datetime(df['Activity_Period'], format='%Y%m')
SlurpGoose
  • 90
  • 1
  • 7