最近有个需求是获取明年的当天,随便记录一下
from datetime import *
# 获取当前时间
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 2022-06-29 17:20:14
# 获取年份
now_year = datetime.now().year # 2022
# 然后用当前时间替换即可
n = 1 # 表示1年以后
n_year_later = datetime.now().replace(year=datetime.now().year+n).strftime("%Y-%m-%d %H:%M:%S") # 2023-06-29 17:20:14
有更好的方法可以分享一下!
顺便列一下datetime
模块的常用方法
创建时间
# 获取当前时间
import datetime
datetime.datetime.now() # 获取当前日期及时间
datetime.date.today() or datetime.date.now().date() # 获取当前日期
# 创建特定时间
import datetime
datetime.datetime(1992, 4, 12, 4, 23, 34, 888888)
datetime.date(1992, 4, 12)
time = datetime.time(4, 23, 34, 888888)
# 修改某一时间的年月日、时分秒(replace)
time.replace(hour = 5) # return datetime.time(5, 23, 34, 888888)
# 均可以少参数,按年月日、时分秒从左往右依次读取,没有按0处理
datetime与str之间类型转换
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类型
datetime.datetime.strptime('2022-06-29', '%Y-%m-%d') # return datetime.datetime(2022, 6, 29, 0, 0)
# %a: 星期的简写
# %A: 星期的完整写法
# %c: 用字符串表示日期和时间(Tue Aug 16 21:30:00 2014)
# %x: 用字符串表示日期(08/16/14)
# %X: 用字符串表示时间(21:30:00)
# %f: 微秒
# %I: 12小时制的小时,与%H那里可以换着使用
# %p: AM/PM
# %w: 本周的第几天
# %W: 本年的第几周(周一是第一天)
# %U: 本年的第几周(周日是第一天)
# %j: 今年的第几天
# %z: 与 UTC 时间的间隔 ;如果是本地时间,返回空字符串((empty), +0000, -0400, +1030)
# %Z: 时区名称;如果是本地时间,返回空字符串((empty), UTC, EST, CST)
# %%: 表示百分号