Home > front end >  Converting String to datetime (from Week number/Year to dd/mm/yy) in a pandas DataFrame
Converting String to datetime (from Week number/Year to dd/mm/yy) in a pandas DataFrame

Time:02-25

I have the following DataFrame

example = {"Time":["01/2021","02/2021","04/2021","05/2021"]}
df = pd.DataFrame( example )


    Time
0   01/2021
1   02/2021
2   04/2021
3   05/2021

Column Time is composed by strings. Each string is composed by week number (from 1 to 52) and Year.

I would like to convert to dd/mm/yyyy

    Time    Time Converted 
0   01/2021  10/01/2021
1   02/2021  17/01/2021
2   04/2021  24/01/2021
3   05/2021  31/01/2021
  1. How can I do that?

  2. How to chose the dd if it should be Monday or Sunday? Like in the following alternative output?

         Time    Time Converted 
    0    01/2021  04/01/2021
    1    02/2021  11/01/2021
    2    04/2021  18/01/2021
    3    05/2021  25/01/2021
    

I tried to find any other question specifically dealing with the week number, but I couldn't find it.

If this is a duplicate please let me know :)

CodePudding user response:

You can use pd.to_datetime:

df['Time Converted'] = pd.to_datetime('1/'   df['Time'], format='%w/%U/%Y')
print(df)

# Output
      Time Time Converted
0  01/2021     2021-01-04
1  02/2021     2021-01-11
2  04/2021     2021-01-25
3  05/2021     2021-02-01
  • %w: Weekday number
  • %U: Week number of the year
  • %Y: Year

Update

I would like to get the last day of the week and not Monday. (e.g. 10/01/2021 instead of 04/01/2021).

df['Time Converted'] = pd.to_datetime('0/'   df['Time'], format='%w/%U/%Y') \
                         pd.DateOffset(days=7)
print(df)

# Output
      Time Time Converted
0  01/2021     2021-01-10
1  02/2021     2021-01-17
2  04/2021     2021-01-31
3  05/2021     2021-02-07

Note: adjust the day of the week (0, 1 or 6) according to your locale.

  • Related