如何基于用户输入的结束日期生成%Y%m%d格式的次日日期
To generate NEXT_DATE as the day after your input END_DATE in %Y%m%d format, you can use Python's datetime.timedelta class to add one day to the parsed datetime object of END_DATE, then format it to the required string format. Here's how to adjust your code:
First, ensure you have imported the datetime module at the top of your script (it’s required for date parsing and manipulation):
import datetime
Then update your dates_sec() function to compute and return the next date alongside your existing start and end dates:
def dates_sec(): START_DATE = str(input('Enter start date in %Y-%m-%d %H:%M:%S format: ')) END_DATE = str(input('Enter end date in %Y-%m-%d %H:%M:%S format: ')) try: # Parse input strings into proper datetime objects start_dt = datetime.datetime.strptime(START_DATE, '%Y-%m-%d %H:%M:%S') end_dt = datetime.datetime.strptime(END_DATE, '%Y-%m-%d %H:%M:%S') # Convert to YYYYMMDD string format for SD and ED start_date = start_dt.strftime('%Y%m%d') end_date = end_dt.strftime('%Y%m%d') # Calculate the next date by adding 1 day to end_dt next_dt = end_dt + datetime.timedelta(days=1) next_date = next_dt.strftime('%Y%m%d') print('Dates accepted!') return start_date, end_date, next_date except ValueError: raise ValueError("Incorrect date format, should be YYYY-MM-DD HH:MM:SS") # Assign the returned values to your variables SD, ED, NEXT_DATE = dates_sec() # Optional: Verify the results print(f"Start Date: {SD}") print(f"End Date: {ED}") print(f"Next Date: {NEXT_DATE}")
Key Details:
- Automatic Edge Case Handling: Using
timedelta(days=1)takes care of month/year transitions automatically (like July 31 → August 1) without you having to write custom logic for month lengths or leap years. - Clarity: Renamed parsed datetime variables to
start_dt/end_dtto distinguish them from the original input string variables, making the code easier to follow. - Consistent Formatting: The next date uses the same
strftime('%Y%m%d')method as your existing dates, ensuring consistent output.
Testing with your example input:
Enter start date in %Y-%m-%d %H:%M:%S format: 2018-07-01 00:00:00
Enter end date in %Y-%m-%d %H:%M:%S format: 2018-07-31 00:00:00
You’ll get the expected output:
Dates accepted! Start Date: 20180701 End Date: 20180731 Next Date: 20180801
内容的提问来源于stack exchange,提问作者some_programmer

