pandas Python中的日期格式- YYYYWW到DD/MM/YYYY

k3bvogb1  于 2023-06-28  发布在  Python
关注(0)|答案(4)|浏览(111)

我正在使用一个Python数据框,其中包含一列格式为YYYYWW的日期。例如,202310,其中2023是年,10是周数。
理想情况下,我希望将其转换为可用的日期格式,如dd/mm/yyyy或dd-mm-yyyy。

kxeu7u2r

kxeu7u2r1#

如果你想要一个随机的日期,你可以试试这个代码-

import random
import datetime
def get_random_day_from_week(year_week):
    year = int(year_week[:4])
    week = int(year_week[4:])

    # Get the first day of the given week and year
    first_day = datetime.datetime.strptime(f'{year}-W{week-1}-1', "%Y-W%W-%w").date()

    # Get a random day within the week
    random_day = first_day + datetime.timedelta(days=random.randint(0, 6))

    return random_day.strftime("%d/%m/%Y")

year_week = "202326"
random_day = get_random_day_from_week(year_week)
print(random_day)
bxjv4tth

bxjv4tth2#

你可以使用类似这样的东西:

from datetime import date

date_str='202310'
year=int(date_str[:4])
week=int(date_str[4:])
day_of_week=1 # set a value, 1 for Monday

Sample_date=date.fromisocalendar(year, week, day_of_week)
print(Sample_date.year,'/',Sample_date.month,'/',Sample_date.day) #format as you wish
qojgxg4l

qojgxg4l3#

或者,您也可以执行以下操作。

from datetime import datetime, date, timedelta

date_str='202310'
year=int(date_str[:4])
week=int(date_str[4:])

# function finds first Monday of the month given the date passed in "today"
def find_first_monday(year, month=1, day=1):
    d = datetime(int(year), int(month), int(day))
    offset = 0-d.weekday() #weekday = 0 means monday
    if offset < 0:
        offset+=7
    return d+timedelta(offset)

# converts datetime object to date
first_monday_of_year = find_first_monday(year).date()

# prints the next Monday given the date that is passed as "today" 

print(f'First Monday of the year date: {first_monday_of_year}')

#Calculate number of days from the first monday of the year to the week specified 

days_after_n_weeks = (week-1) * 7

# Add the number of days to the first date of the week
converted_date = first_monday_of_year + timedelta(days_after_n_weeks)
print(f'Date of a Monday in Week {week} of year {year} is {converted_date}')

这个想法是你找到一周的第一个星期一的日期。将周数添加到日期以达到指定周的第一个星期一。

2ledvvac

2ledvvac4#

因为你只有年份和周数,所以你必须决定哪一天。假设你选择星期一,那么你可以这样做:

df["Date"] = pd.to_datetime(df["Date"] + "1", format="%Y%W%w")

"1"添加到字符串中,然后使用pd.to_datetime将结果转换为%Y%W%w%Y-年份和世纪,%W-星期零填充,%w-星期日(这里总是1,即星期一)。
对于以下示例 Dataframe

df = pd.DataFrame({"Date": [f"2023{n:0>2}" for n in range(1, 10)]})
Date
0  202301
1  202302
2  202303
3  202304
4  202305
5  202306
6  202307
7  202308
8  202309
9  202310

结果将是

Date
0 2023-01-02
1 2023-01-09
2 2023-01-16
3 2023-01-23
4 2023-01-30
5 2023-02-06
6 2023-02-13
7 2023-02-20
8 2023-02-27
9 2023-03-06

相关问题