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)
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
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}')
4条答案
按热度按时间kxeu7u2r1#
如果你想要一个随机的日期,你可以试试这个代码-
bxjv4tth2#
你可以使用类似这样的东西:
qojgxg4l3#
或者,您也可以执行以下操作。
这个想法是你找到一周的第一个星期一的日期。将周数添加到日期以达到指定周的第一个星期一。
2ledvvac4#
因为你只有年份和周数,所以你必须决定哪一天。假设你选择星期一,那么你可以这样做:
将
"1"
添加到字符串中,然后使用pd.to_datetime
将结果转换为%Y%W%w
:%Y
-年份和世纪,%W
-星期零填充,%w
-星期日(这里总是1,即星期一)。对于以下示例 Dataframe
结果将是