Python 日期 的 加减 等 操作

datetime — Basic date and time types:https://docs.python.org/3.8/library/datetime.html

dateutil --- powerful extensions to datetime:https://dateutil.readthedocs.io/en/stable/index.html

Python time 和 datetime 的常用转换处理:https://www.cnblogs.com/lxmhhy/p/6030730.html

  • datetime 转 timestamp
  • datetime 转 时间字符串
  • timestamp 转 datetime
  • timestamp 转 时间字符串
  • 时间字符串 转 datetime
  • 时间字符串 转 timestamp

对于这三者的转换,python2和python3是不同的,因为在python3中新增一些实例方法,能够很方便的实现这些类型之间的转换。

如果需要python2的类型转换请移步这些文章:
python --- 时间与时间戳之间的转换:https://blog.csdn.net/google19890102/article/details/51355282
Python 字符串、时间戳、datetime 时间相关转换:https://blog.csdn.net/Data_Ada/article/details/72900019

简单介绍下,datetime 和 time 中常用的方法

  • datetime.datetime.strptime(string, format)。类方法,作用是根据指定的format(格式),将字符串转换成datetime.datetime实例对象。
  • datetime.datetime.strftime(format): 实例方法,作用就是根据指定的format(格式),将datetime.datetime实例对象转换成时间字符串。
  • datetime.datetime.timestamp(): 实例方法,作用就是将datetime.datetime实例对象转换成时间戳。
  • datetime.fromtimestamp(timestamp, tz=None):类方法,作用是将时间戳转换成datetime.datetime对象。
  • time.strptime(string, format)。类方法,作用是根据指定的format(格式)将时间字符串转换成time.struct_time对象。
  • time.strftime(format, string)。类方法,作用是根据指定的format(格式,)将time.struct_time对象转换成时间字符串。
  • time.localtime(timestamp)。类方法,作用是将时间戳转换成本地时间的time.struct_time对象。若要转换成UTC的time.struct_time对象则使用time.gtime()。
  • time.mktime(t)。类方法,time.localtime()的逆函数,因为作用正好相反。其作用是将time.struct_time对象转换成时间戳。

示例:

# 把 datetime 转成 字符串
def datetime_toString(dt):
    return dt.strftime("%Y-%m-%d-%H")
 
# 把 字符串 转成 datetime
def string_toDatetime(string):
    return datetime.strptime(string, "%Y-%m-%d-%H")
 
# 把 字符串 转成 时间戳形式
def string_toTimestamp(strTime):
    return time.mktime(string_toDatetime(strTime).timetuple())
 
# 把 时间戳 转成 字符串形式
def timestamp_toString(stamp):
    return time.strftime("%Y-%m-%d-%H", tiem.localtime(stamp))
 
# 把 datetime类型 转成 时间戳形式
def datetime_toTimestamp(dateTim):
    return time.mktime(dateTim.timetuple())

datetime timestamp

直接使用 datetime 模块中 datetime类 的 timestamp() 实例方法。

import datetime
import time

dt = datetime.datetime.now()
ts = dt.timestamp()
print(f'{type(dt)} : {dt}')  
print(ts)               

datetime 时间字符串

直接使用 datetime 模块中的 datetime类 的 strftime() 实例方法即可。

import datetime
import time

dt = datetime.datetime.now()

# 根据此格式来解析datetime.datetime()对象为时间字符串
format_string = '%Y-%m-%d %H:%M:%S'

print(f'{type(dt)} : {dt}')
print(dt.strftime(format_string))

timestamp datetime

import datetime
import time

ts = 1568172006.68132  # 时间戳
dt = datetime.datetime.fromtimestamp(ts)
print(dt)

timestamp 时间字符串

  1. 如果使用 time 模块,转换必须通过 time.struct_time对象作为桥梁。

  2. 如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成时间字符串。

示例代码:

import datetime
import time

# 方法 1
ts = 1568172006.68132                # 时间戳
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来时间戳解析为时间字符串
# 时间戳转time.struct_time
ts_struct = time.localtime(ts)
# time.struct_time 转时间字符串
date_string = time.strftime(format_string, ts_struct)

print(date_string)  # '2019-09-11 11:20:06'

# 方法 2
dt = datetime.datetime.fromtimestamp(ts)
date_string = dt.strftime(format_string)

时间字符串datetime

只需要使用 datetime模块 中的 datetime类 的 strptime(date_string, format)类方法即可。
这个方法的作用就是:根据指定的 format 格式将时间字符串 date_string,转换成 datetime.datetime()对象。

import datetime
import time

date_string = '2019-09-11 11:20:06'
# 根据此格式来解析时间字符串为datetime.datetime()对象
format_string = '%Y-%m-%d %H:%M:%S'

dt = datetime.datetime.strptime(date_string, format_string)
print(dt)  # datetime.datetime(2019, 9, 11, 11, 20, 6)

时间字符串timestamp

  1. 方法 1:如果使用 time 模块,转换必须通过 time.struct_time 对象作为桥梁。

  2. 方法 2:如果使用 datetime 模块,先转成 datetime.datetime 对象,再转成 timestamp。

示例代码:

import datetime
import time

# 方法 1
date_string = '2019-09-11 11:20:06'
format_string = '%Y-%m-%d %H:%M:%S'  # 根据此格式来解析时间字符串为time()对象

# 时间字符串转 time.struct_time
ts_struct = time.strptime(date_string, format_string)
# time.struct_time 转时间戳
ts = time.mktime(ts_struct)
print(ts)  # 1568172006.0

# 方法 2
dt = datetime.datetime.strptime(date_string, format_string)
ts = dt.timestamp()

日期输出格式化

所有日期、时间的 api 都在 datetime 模块内。

1. datetime  ----->  string

import datetime


if __name__ == '__main__':
    now = datetime.datetime.now()
    t = now.strftime('%Y-%m-%d %H:%M:%S')
    print(type(t), t)


# 结果:<class 'str'> 2019-12-13 14:08:35

strftime 是 datetime类 的实例方法。

import time

time.strftime

"""
strftime(format[, tuple]) -> string

Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.

Commonly used format codes:

%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's equivalent of either AM or PM.

Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

time.strptime

"""
strptime(string, format) -> struct_time

Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).

Commonly used format codes:

%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23].
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61].
%z  Time zone offset from UTC.
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.
%b  Locale's abbreviated month name.
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.
%I  Hour (12-hour clock) as a decimal number [01,12].
%p  Locale's equivalent of either AM or PM.

Other codes may be available on your platform.  See documentation for
the C library strftime function.
"""

更多 time() 模块函数,可以查看 time() 模块

2. string  ----->  datetime

import datetime


if __name__ == '__main__':
    t_str = '2012-03-05 16:26:23'
    d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
    print(type(d), d)


# 结果:<class 'datetime.datetime'> 2012-03-05 16:26:23

strptime 是 datetime类 的 静态方法。

日期比较操作

在 datetime 模块中有 timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别。

构造方法:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

所有的参数都有默认值0,这些参数可以是int或float,正的或负的。

可以通过 timedelta.days、tiemdelta.seconds 等获取相应的时间值。

timedelta类的实例支持加、减、乘、除等操作,所得的结果也是 timedelta类 的 实例。比如:

year = timedelta(days=365)
ten_years = year *10
nine_years = ten_years - year

同时,date、time 和 datetime 类也支持与 timedelta 的加、减运算。

datetime1 = datetime2 +/- timedelta
timedelta = datetime1 - datetime2

这样,可以很方便的实现一些功能。

1. 两个日期相差多少天。

import datetime


if __name__ == '__main__':
    d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
    d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
    delta = d1 - d2        
    print(type(delta), delta.days)


# 结果:<class 'datetime.timedelta'> 3

2. 今天的 n 天后的日期。

import datetime


if __name__ == '__main__':
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=3)
    n_days = now + delta
    print(n_days.strftime('%Y-%m-%d %H:%M:%S'))


# 结果:2019-12-16 14:14:06

示例代码:

import datetime

now = datetime.datetime.now()
print(now)

# 将日期转化为字符串 datetime => string
print(now.strftime('%Y-%m-%d %H:%M:%S'))

t_str = '2012-03-05 16:26:23'
# 将字符串转换为日期 string => datetime
d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
print(d)

# 在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日#期或者时间的差别。

# 计算两个日期的间隔
d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
delta = d1 - d2
print(delta.days)
print(delta)

# 今天的n天后的日期。
now = datetime.datetime.now()
delta = datetime.timedelta(days=3)
n_days = now + delta
print(n_days.strftime('%Y-%m-%d %H:%M:%S'))


# 结果
# 2019-12-13 14:23:35.819567
# 2019-12-13 14:23:35
# 2012-03-05 16:26:23
# 3
# 3 days, 0:00:00
# 2019-12-16 14:23:35

示例代码 :

import time
import datetime


if __name__ == '__main__':
    now_time = datetime.datetime.now()  # 当前时间
    now_time_mk = time.mktime(now_time.timetuple())  # 当前时间戳
    
    current_month = now_time.month

    # 下月第一天最后一秒时间
    if current_month == 12:        
        next_mouth_first_day = datetime.datetime(now_time.year + 1, 1, 1, 23, 59, 59)
    else:
        next_mouth_first_day = datetime.datetime(now_time.year, current_month + 1, 1, 23, 59, 59)

    # 当前月最后一天
    current_month_last_day = next_mouth_first_day - datetime.timedelta(days=1)
    # 当前月第一天
    current_month_first_day = datetime.date(now_time.year, now_time.month, 1)
    # 前一月最后一天
    pre_month_last_day = current_month_first_day - datetime.timedelta(days=1)
    # 前一月第一天
    pre_month_first_day = datetime.date(pre_month_last_day.year, pre_month_last_day.month, 1)

    print(next_mouth_first_day)
    print(current_month_last_day)
    print(current_month_first_day)
    print(pre_month_last_day)
    print(pre_month_first_day)

'''
结果:
2020-01-01 23:59:59
2019-12-31 23:59:59
2019-12-01
2019-11-30
2019-11-01
'''

Python GMT时间格式转化

datetime 类型转换成 GMT 时间格式的字符串(如'Thu, 19 Feb 2009 16:00:07 GMT'),strftime(官方释义:new string) :

from datetime import datetime
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT+0800 (CST)'
 
print(datetime.utcnow().strftime(GMT_FORMAT))
 
output:
Mon, 12 Nov 2018 08:53:51 GMT+0800 (CST)

将GMT时间格式的字符串转换成datetime类型,strptime(官方释义:new datetime parsed from a string):

dd = "Fri Nov 09 2018 14:41:35 GMT+0800 (CST)"
GMT_FORMAT = '%a %b %d %Y %H:%M:%S GMT+0800 (CST)'
print(datetime.strptime(dd, GMT_FORMAT))
 
output:
2018-11-09 14:41:35

注意:GMT_FORMAT的格式要与索要转化的字符串相对应。

扩展:python的格式转化

%a 本地的星期缩写
%A 本地的星期全称
%b 本地的月份缩写
%B 本地的月份全称
%c 本地的合适的日期和时间表示形式
%d 月份中的第几天,类型为decimal number(10进制数字),范围[01,31]
%f 微秒,类型为decimal number,范围[0,999999],Python 2.6新增
%H 小时(24进制),类型为decimal number,范围[00,23]
%I 小时(12进制),类型为decimal number,范围[01,12]
%j 一年中的第几天,类型为decimal number,范围[001,366]
%m 月份,类型为decimal number,范围[01,12]
%M 分钟,类型为decimal number,范围[00,59]
%p 本地的上午或下午的表示(AM或PM),只当设置为%I(12进制)时才有效
%S 秒钟,类型为decimal number,范围[00,61](60和61是为了处理闰秒)
%U 一年中的第几周(以星期日为一周的开始),类型为decimal number,范围[00,53]。在度过新年时,直到一周的全部7天都在该年中时,才计算为第0周。只当指定了年份才有效。
%w 星期,类型为decimal number,范围[0,6],0为星期日
%W 一年中的第几周(以星期一为一周的开始),类型为decimal number,范围[00,53]。在度过新年时,直到一周的全部7天都在该年中时,才计算为第0周。只当指定了年份才有效。
%x 本地的合适的日期表示形式
%X 本地的合适的时间表示形式
%y 去掉世纪的年份数,类型为decimal number,范围[00,99]
%Y 带有世纪的年份数,类型为decimal number
%Z 时区名字(不存在时区时为空)
%% 代表转义的"%"字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值