如何以YYYY-MM-DD格式打印10个从今日起间隔两周的日期
Generate 10 Dates Spaced Two Weeks Apart (Starting from Today)
To generate 10 dates starting from the current date, with each date two weeks (14 days) apart and formatted as YYYY-MM-DD, you can use Python's datetime module. Here's the corrected and complete code:
import datetime # Get today's date (without time component) current_date = datetime.date.today() # Generate and print 10 dates, each 2 weeks apart for i in range(10): # Calculate the date by adding i * 14 days to today's date target_date = current_date + datetime.timedelta(days=i * 14) # Print the date in YYYY-MM-DD format print(target_date)
How this works:
datetime.date.today()gives us the current date (e.g.,2024-05-20) without any time information, which is exactly what we need for theYYYY-MM-DDformat.datetime.timedelta(days=i * 14)creates a time interval ofimultiplied by 14 days. Fori=0, this adds 0 days (so we get today's date),i=1adds 14 days, up toi=9which adds 126 days (9 weeks later).- Printing the
target_dateobject directly outputs it in theYYYY-MM-DDformat since that's the default string representation of adateobject in Python.
If you prefer to start from the first date two weeks from today instead of including today, just adjust the loop to start at 1 instead of 0:
for i in range(1, 11): target_date = current_date + datetime.timedelta(days=i * 14) print(target_date)
内容的提问来源于stack exchange,提问作者Nitish Attri
相关产品推荐
相关产品推荐

