Home > Enterprise >  Converting TimeFormat 'DD/MM/YY HH:MM AM' from String in Python to Datetime 'DD/MM/YY
Converting TimeFormat 'DD/MM/YY HH:MM AM' from String in Python to Datetime 'DD/MM/YY

Time:05-10

sorry am new here and a total Python Rookie.

I pull Data with Python from Jira and put it into DataFrame. There I have a datetime as string in following format: DD/MM/YY HH:MM AM (or PM). Now I want to convert to Datetime to make it comparable with other datetimes to DD/MM/YY HH:MM:SS. I wanted to use datetime.strptime but it always fails. Any ideas? Thanks in advance!

CodePudding user response:

Use a custom format: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

from datetime import datetime

datetime.strptime("05/11/22 07:40 AM", "%d/%m/%y %I:%M %p")
# datetime.datetime(2022, 11, 5, 7, 40) 

datetime.strptime("05/11/22 07:40 PM", "%d/%m/%y %I:%M %p")
# datetime.datetime(2022, 11, 5, 19, 40)

CodePudding user response:

You mention "DataFrame", so I guess you are using pandas. In that case, you should not have to do much work yourself. Just point pandas' read_* function to the column(s) that contain datetime-like strings. With argument dayfirst=True you make sure that dates are inferred as DD/MM/YY, not MM/DD/YY:

df = pd.read_csv(StringIO("""\
when,value
11/05/22 07:40 AM,42
10/05/22 09:42 AM,8
09/05/22 08:41 AM,15
"""), parse_dates=['when'], dayfirst=True)

This yields the following DataFrame, df.dtypes containing a nice datetime64[ns] for column "when".

    when    value
0   2022-05-11 07:40:00     42
1   2022-05-10 09:42:00     8
2   2022-05-09 08:41:00     15

If you already have the DataFrame with a string column, you can convert it after the fact using

df["when"] = pd.to_datetime(df["when"], dayfirst=True)
  • Related