简体   繁体   English

如何将年和周转换为日期类型?

[英]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.

相关问题 如何将日期转换为年份之后的星期数? - How to convert date to week number that follow the year? 如何将周/年(10/2018)转换为日期格式 - how to convert Week/Year (10/2018) to date format 如何在熊猫数据框中将日期类型从“year_week”更改为“day_month_year”格式? - How to change date type from 'year_week' to 'day_month_year' format in pandas dataframe? 如何将星期几、月份、日期转换为年 - 月 - 日期 - How can I convert day of week, Month, Date to Year - Month - Date Pyspark 将年和周数转换为 week_start 日期和 week_end 日期 - Pyspark convert Year and week number to week_start Date & week_end Date 在 Pandas 中将原始日期转换为年/月/星期几 - Convert Raw Date into Year / Month / Day of Week in Pandas 将年周至今的条件转换为该周中该月的最大天数的日期 - Convert year-week to date condition to date where the week has max days for that month Pandas to_datetime 将年-周转换为 2019 年的日期,第一周是 wk0 - Pandas to_datetime convert year-week to date in 2019, first week is wk0 解析迄今为止的年周列 - Parse Year Week columns to Date 如何将字符串数据框列转换为datetime作为年份和周的格式? - How to convert string dataframe column to datetime as format with year and week?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM