[英]How to convert year and week to date type?
I load the attached excel file into python, but it does not detect the values in the cell in date format.我将附加的 excel 文件加载到 python 中,但它没有检测到日期格式的单元格中的值。
It treats cell values as Object.它将单元格值视为 Object。
How can I convert the year and week in the attached file (eg 2018(year)-16(week) to date type for use in python?如何将附件中的年和周(例如 2018(年)-16(周))转换为日期类型以用于 python?
I used the code below but it is not working.我使用了下面的代码,但它不起作用。
import datetime
def to_datetime(x):
return datetime.datetime.strptime(x + '-1', "%Y-%W-%w")
train['date'] = train['date'].apply(to_datetime)
Based on https://stackoverflow.com/a/17087427/15035314基于https://stackoverflow.com/a/17087427/15035314
import pandas as pd
train = pd.DataFrame({'date': [f'2018-{i}' for i in range(16, 25)]})
train['date'] = pd.to_datetime(train['date']+'-1', format='%Y-%W-%w',errors='coerce')
print(train)
date
0 2018-04-16
1 2018-04-23
2 2018-04-30
3 2018-05-07
4 2018-05-14
5 2018-05-21
6 2018-05-28
7 2018-06-04
8 2018-06-11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.