日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 日期 的 加减 等 操作

發布時間:2024/7/23 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 日期 的 加减 等 操作的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。