在Python中格式化日期 – YYYYWW 到 DD/MM/YYYY

huangapple go评论81阅读模式
英文:

Formatting dates in Python - YYYYWW to DD/MM/YYYY

问题

我正在使用一个包含日期列的Python数据帧,日期的格式是YYYYWW。例如,202310其中2023是年份,10是周数。

理想情况下,我想将其转换为可用的日期格式,如dd/mm/yyyy或dd-mm-yyyy。

英文:

I'm working with a Python dataframe which includes a column of dates that are formatted as YYYYWW. For example, 202310 where 2023 is the year and 10 is the week number.

Ideally I would like to convert this to a usable date format such as dd/mm/yyyy or dd-mm-yyyy.

答案1

得分: 1

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)
英文:

If you want a random date of that week, you can try this code out-

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)

答案2

得分: 0

你可以使用类似这样的代码:

from datetime import date

date_str = '202310'
year = int(date_str[:4])
week = int(date_str[4:])
day_of_week = 1  # 设置一个值,1代表星期一

Sample_date = date.fromisocalendar(year, week, day_of_week)
print(Sample_date.year, '/', Sample_date.month, '/', Sample_date.day)  # 格式化为你希望的方式
英文:

You can use something like this:

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

答案3

得分: 0

以下是您要翻译的代码部分:

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 the number of days from the first Monday of the year to the specified week
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}')

如果您需要进一步的翻译或解释,请告诉我。

英文:

Alternatively, you can also do the following.

from datetime import datetime, date, timedelta

date_str=&#39;202310&#39;
year=int(date_str[:4])
week=int(date_str[4:])


# function finds first Monday of the month given the date passed in &quot;today&quot;
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 &lt; 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 &quot;today&quot; 

print(f&#39;First Monday of the year date: {first_monday_of_year}&#39;)

#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&#39;Date of a Monday in Week {week} of year {year} is {converted_date}&#39;)

The idea is that you find the date for the first Monday of the week. Add the number of weeks to the date to reach the first Monday in the specified week.

答案4

得分: 0

以下是您要翻译的部分:

"Since you only have the year and the week number, you have to make a decision about the day. Lets say you pick Monday, then you could do:"

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

Add a &quot;1&quot; to the strings and then use pd.to_datetime to convert the result by using the format %Y%W%w: %Y - year with century, %W - week zero-padded, %w - weekday (here always 1, ie. Monday).

For the following sample dataframe

df = pd.DataFrame({&quot;Date&quot;: [f&quot;2023{n:0&gt;2}&quot; 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

the result would be

        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
英文:

Since you only have the year and the week number, you have to make a decision about the day. Lets say you pick Monday, then you could do:

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

Add a &quot;1&quot; to the strings and then use pd.to_datetime to convert the result by using the format %Y%W%w: %Y - year with century, %W - week zero-padded, %w - weekday (here always 1, ie. Monday).

For the following sample dataframe

df = pd.DataFrame({&quot;Date&quot;: [f&quot;2023{n:0&gt;2}&quot; 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

the result would be

        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

huangapple
  • 本文由 发表于 2023年6月27日 21:07:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76565210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定