首页 > 其他分享 >时间增减计算

时间增减计算

时间:2022-11-27 23:55:47浏览次数:30  
标签:-% 11 datetime 时间 计算 增减 print now

1. 使用datetime.timedelta()方法

使用datetime库的timedelta()方法,支持:周、天、时、分、秒、毫秒、微秒
# 当前系统时间
import datetime
now = datetime.datetime.now()
print("当前时间:", now)
# 格式化时间
now_strf = now.strftime("%Y-%m-%d %H:%M:%S")
print("当前时间格式化:", now_strf)

'''
加减日期使用datetime库的timedelta()方法,支持:周、天、时、分、秒、毫秒、微秒
datetime.timedelta()支持:days,seconds,microseconds,milliseconds,minutes,hours,weeks
'''
# 时间加一天
tomorrow = (now + datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
print("明天:", tomorrow)

# 时间减一天
yesterday = (now + datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S")
print("昨天:", yesterday)

当前时间: 2022-11-27 21:12:57.870777
当前时间格式化: 2022-11-27 21:12:57
明天: 2022-11-28 21:12:57
昨天: 2022-11-26 21:12:57

2. 使用第三方库dateutil

需先安装dateutil库:pip install python-dateutil

relativedelta()支持years,months,days,leapdays闰日,weeks,hours,minutes,seconds,microsends

# pip install python-dateutil
import datetime
from dateutil.relativedelta import relativedelta
"""
relativedelta()支持years,months,days,leapdays闰日,weeks,hours,minutes,seconds,microsends
"""
now = datetime.datetime.now()
print("现在:", now.strftime("%Y-%m-%d %H:%M:%S"))

# 时间减一年
last_year = (now - relativedelta(years=1)).year
print("去年:", last_year)

# 时间加一年
next_year = (now + relativedelta(years=1)).year
print("明年:", next_year)
next_year_now = (now + relativedelta(years=1)).strftime("%Y-%m-%d %H:%M:%S")
print("明年此时:", next_year_now)

# 指定时间往前2个月
d = datetime.datetime.strptime("20180629", "%Y%m%d")
print(d)
d2 = (d - relativedelta(months=2)).strftime("%Y-%m-%d")
print(d2)

现在: 2022-11-27 21:11:58
去年: 2021
明年: 2023
明年此时: 2023-11-27 21:11:58
2018-06-29 00:00:00
2018-04-29

3. 时区转换

import datetime

# 世界标准时间
utc_now = datetime.datetime.utcnow()
print("当前时间(世界时间):", utc_now)

# 方法一
now_zone = utc_now.replace(tzinfo=datetime.timezone.utc).astimezone(
    datetime.timezone(
        datetime.timedelta(hours=8)
    )
)
print("当前时间(北京时间):", now_zone)

# 方法二
now_time1 = utc_now + datetime.timedelta(hours=8)
print("当前时间(北京时间):", now_time1)

# 方法三
import pytz		# pip install pytz
# print(pytz.all_timezones)		# 所有时区
now_time2 = datetime.datetime.now(pytz.timezone("Asia/Shanghai"))	# 东八区
print("当前时间(北京时间):", now_time2)

当前时间(世界时间): 2022-11-27 15:44:17.361356
当前时间(北京时间): 2022-11-27 23:44:17.361356+08:00
当前时间(北京时间): 2022-11-27 23:44:17.361356
当前时间(北京时间): 2022-11-27 23:44:17.377282+08:00

 

标签:-%,11,datetime,时间,计算,增减,print,now
From: https://www.cnblogs.com/rider-zhou/p/16930701.html

相关文章