Home > Net >  Convert str data to proper format
Convert str data to proper format

Time:08-03

I have a Input like

"3-August 202212.00 PM"

Expected output :

"03-08-2022,12:00:00PM"

Any suggestion recommended. I tried to convert to datetime and after strftime.But it not works due to 202212.00 pm.

Final output type will be str not datetime

Thanks in advance

CodePudding user response:

strftime works, you just need to use the correct directives in both directions:

from datetime import datetime

date = datetime.strptime('3-August 202212.00 PM',
                         '%d-%B %Y%I.%M %p')

print(date.strftime('%d-%m-%Y,%I:%M:%S%p'))

outputs

'03-08-2022,12:00:00PM'

CodePudding user response:

You can use datetime to get the result in 2 steps:

  1. convert str to datetime format
  2. convert datetime object to str in the new format
import datetime as dt
x = "3-August 202212.00 PM"

x = dt.datetime.strptime(x, "%d-%B %Y%I.%M %p").strftime("%d-%m-%Y,%I:%M:%S %p")
print(x)

Output:

03-08-2022,12:00:00 PM

If you have a pd.DataFrame with given strings, you can do as follows: Supposed we have a DataFrame with the following output:

import pandas as pd
y = pd.DataFrame(["3-August 202212.00 PM", "3-March 202104.00 AM", "6-July 202202.00 PM", "23-December 202009.00 AM", "27-May 201806.50 PM"], columns=['Date'])
>>> y
    Date
0   3-August 202212.00 PM
1   3-March 202104.00 AM
2   6-July 202202.00 PM
3   23-December 202009.00 AM
4   27-May 201806.50 PM

Use:

y = pd.to_datetime(y.Date, format='%d-%B %Y%I.%M %p', errors='coerce').apply(lambda x: x.strftime("%d-%m-%Y,%I:%M:%S %p"))
print(type(y))
# pd.to_datetime returns type pandas.core.series.Series so y need to be converted back to dataframe
y = pd.DataFrame(y)

will give a result:

>>> y
    Date
0   03-08-2022,12:00:00 PM
1   03-03-2021,04:00:00 AM
2   06-07-2022,02:00:00 PM
3   23-12-2020,09:00:00 AM
4   27-05-2018,06:50:00 PM

Note: Need to be careful when converting hour. in this case you will want to use %I instead of %H since:

%I : Hour (12-hour clock) as a zero-padded decimal number.

%H : Hour (24-hour clock) as a zero-padded decimal number.

  • Related