欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

Python 日期 的 加减 等 操作

发布时间:2024/7/23 python 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 timedt = datetime.datetime.now() ts = dt.timestamp() print(f'{type(dt)} : {dt}') print(ts)

 

 

datetime 时间字符串

 

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

import datetime import timedt = 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 timets = 1568172006.68132 # 时间戳 dt = datetime.datetime.fromtimestamp(ts) print(dt)

 

 

timestamp 时间字符串

 

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

  • 如果使用 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 timedate_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:如果使用 time 模块,转换必须通过 time.struct_time 对象作为桥梁。

  • 方法 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 datetimeif __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]) -> stringConvert 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_timeParse 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 datetimeif __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 datetimeif __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 datetimeif __name__ == '__main__':now = datetime.datetime.now()delta = datetime.timedelta(days=3)n_days = now + deltaprint(n_days.strftime('%Y-%m-%d %H:%M:%S'))# 结果:2019-12-16 14:14:06

    示例代码:

    import datetimenow = 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 datetimeif __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 日期 的 加减 等 操作的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。