简体   繁体   中英

Python - Converting a column with weekly data to a datetime object

I have the following date column that I would like to transform to a pandas datetime object. Is it possible to do this with weekly data? For example, 1-2018 stands for week 1 in 2018 and so on. I tried the following conversion but I get an error message: Cannot use '%W' or '%U' without day and year

import pandas as pd

df1 = pd.DataFrame(columns=["date"])
df1['date'] = ["1-2018", "1-2018", "2-2018", "2-2018", "3-2018", "4-2018", "4-2018", "4-2018"]

df1["date"] = pd.to_datetime(df1["date"], format = "%W-%Y")

You need to add a day to the datetime format

df1["date"] = pd.to_datetime('0' + df1["date"], format='%w%W-%Y')
print(df1)

Output

        date
0 2018-01-07
1 2018-01-07
2 2018-01-14
3 2018-01-14
4 2018-01-21
5 2018-01-28
6 2018-01-28
7 2018-01-28

As the error message says, you need to specify the day of the week by adding %w:

df1["date"] = pd.to_datetime( '0'+df1.date, format='%w%W-%Y')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM