python 日期 date-str互转以及时间日期的计算

本文介绍如何用Python进行日期和时间的格式转换、计算及时戳处理。涵盖了从字符串到日期对象的转换、日期间的计算及使用relativedelta进行复杂的时间间隔运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

日期格式与字符串互转

# 根据字符串类型转日期 返回值类型<class 'time.struct_time'>
st_time = time.strptime('2019-4-30 11:32:23', '%Y-%m-%d %H:%M:%S')
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=30, tm_hour=11, tm_min=32, tm_sec=23, tm_wday=1, tm_yday=120, tm_isdst=-1) 类型:<class 'time.struct_time'>

# 根据<class 'time.struct_time'>日期类型转字符 返回值类型<class 'str'>
str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(str_time + " 类型:" + str(type(str_time)))
# 2019-04-26 12:33:04 类型:<class 'str'>

# 获取当前日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime()
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=12, tm_min=47, tm_sec=41, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class 'time.struct_time'>

# 获取当前日期时间戳 返回值类型<class 'float'>
float_time = time.time()
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556254126.6432147 类型:<class 'float'>

# 根据<class 'time.struct_time'>日期类型转换为时间戳 返回值类型<class 'float'>
float_time = time.mktime(time.localtime())
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556256409.0 类型:<class 'float'>

# 根据<class 'float'>日期戳转换为struct_time日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime(time.time())
print(str(st_time) + " 类型:" + str(type(st_time)))
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=15, tm_min=5, tm_sec=48, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class 'time.struct_time'>

时间日期的计算

强烈推荐relativedelta

relativedelta 类型旨在应用于现有日期时间,并且可以替换该日期时间的特定组件,或表示时间间隔。
使用简单:

  • 有两种不同的方式来构建 relativedelta 实例。第一个是传递两个日期/日期时间类:
eg:relativedelta(datetime1, datetime2)
  • 第二个是传递任意数量的以下关键字参数:
relativedelta(arg1=x,arg2=y,arg3=z...)

year, month, day, hour, minute, second, microsecond:
    Absolute information (argument is singular); adding or subtracting a
    relativedelta with absolute information does not perform an arithmetic
    operation, but rather REPLACES the corresponding value in the
    original datetime with the value(s) in relativedelta.

years, months, weeks, days, hours, minutes, seconds, microseconds:
    Relative information, may be negative (argument is plural); adding
    or subtracting a relativedelta with relative information performs
    the corresponding arithmetic operation on the original datetime value
    with the information in the relativedelta.

weekday: 
    One of the weekday instances (MO, TU, etc) available in the
    relativedelta module. These instances may receive a parameter N,
    specifying the Nth weekday, which could be positive or negative
    (like MO(+1) or MO(-2)). Not specifying it is the same as specifying
    +1. You can also use an integer, where 0=MO. This argument is always
    relative e.g. if the calculated date is already Monday, using MO(1)
    or MO(-1) won't change the day. To effectively make it absolute, use
    it in combination with the day argument (e.g. day=1, MO(1) for first
    Monday of the month).

leapdays:
    Will add given days to the date found, if year is a leap
    year, and the date found is post 28 of february.

yearday, nlyearday:
    Set the yearday or the non-leap year day (jump leap days).
    These are converted to day/month/leapdays information.

关键字参数有相对形式和绝对形​​式。复数是相对的,单数是绝对的。对于以下顺序中的每个参数,首先应用绝对形式(通过将每个属性设置为该值),然后应用相对形式(通过将值添加到属性)。
将此 relativedelta 添加到日期时间时考虑的属性顺序为:



小时
分钟

微秒
最后,使用上述规则应用工作日。
例如:

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta, MO
>>> dt = datetime(2018, 4, 9, 13, 37, 0)
>>> delta = relativedelta(hours=25, day=1, weekday=MO(1))
>>> dt + delta
datetime.datetime(2018, 4, 2, 14, 37)

使用示例:
date_end = date_start.date() + relativedelta(months=3, days=-1)

返回一个dateutil.relativedelta.relativedelta对象。

timedelta 是datetime中的一个对象,该对象表示两个时间的差值

构造函数:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
其中参数都是可选,默认值为0
其中:

1 millisecond = 1000 microseconds
1 minute = 60 seconds
1 hour = 3600 seconds
1 week = 7 days

在构造函数中,注意参数值的范围:

0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999

import datetime
 
nowtime=datetime.datetime.now()
 
print(nowtime.strftime('%Y-%m-%d %H:%M:%S'))
 
delta=datetime.timedelta(days=1)
 
rs=nowtime+delta
 
print(rs.strftime('%Y-%m-%d %H:%M:%S'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值