Recently, there is a need to obtain the same day next year , Just make a note of it
from datetime import *
# Get the current time
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 2022-06-29 17:20:14
# Get year
now_year = datetime.now().year # 2022
# Then replace it with the current time
n = 1 # Express 1 Years later
n_year_later = datetime.now().replace(year=datetime.now().year+n).strftime("%Y-%m-%d %H:%M:%S") # 2023-06-29 17:20:14
There are better ways to share !
By the way datetime
Common methods of modules
Creation time
# Get the current time
import datetime
datetime.datetime.now() # Get the current date and time
datetime.date.today() or datetime.date.now().date() # Get current date
# Create a specific time
import datetime
datetime.datetime(1992, 4, 12, 4, 23, 34, 888888)
datetime.date(1992, 4, 12)
time = datetime.time(4, 23, 34, 888888)
# Modify the date of a certain time 、 Minutes and seconds (replace)
time.replace(hour = 5) # return datetime.time(5, 23, 34, 888888)
# Can be less parameters , By mm / DD / yy 、 Hours, minutes and seconds are read from left to right , I didn't press 0 Handle
datetime And str Type conversion between
import datetime
time = datetime.datetime.now() # return '2019-09-23 10:27:34.313700'
time.strftime('%Y-%m-%d %H:%M:%S') # return '2022-06-29 17:20:14' str type
datetime.datetime.strptime('2022-06-29', '%Y-%m-%d') # return datetime.datetime(2022, 6, 29, 0, 0)
# %a: Shorthand for the week
# %A: The complete writing of week
# %c: Use a string to represent the date and time (Tue Aug 16 21:30:00 2014)
# %x: Use a string to represent the date (08/16/14)
# %X: Time in a string (21:30:00)
# %f: Microsecond
# %I: 12 An hour system , And %H It can be used interchangeably
# %p: AM/PM
# %w: What day of the week
# %W: The week of the year ( Monday is the first day )
# %U: The week of the year ( Sunday is the first day )
# %j: The first few days of the year
# %z: And UTC Time interval ; If it's local time , Returns an empty string ((empty), +0000, -0400, +1030)
# %Z: Time zone name ; If it's local time , Returns an empty string ((empty), UTC, EST, CST)
# %%: It's a percent sign