c++获取当前时间戳_python开发:python时间模块的使用
生活随笔
收集整理的這篇文章主要介紹了
c++获取当前时间戳_python开发:python时间模块的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:
今天元宵節,祝福大家元宵節快樂。
今天在元宵節給各位朋友分享一下python時間模塊。
我們在開發中經常會與時間打交道,如:獲取事件戳,時間戳的格式化等,這里簡要記錄一下python操作時間的方法。
ython中常見的處理時間的模塊:
- time:處理時間的模塊,如獲取時間戳,格式化日期等
- datetime:date和time的結合體,處理日期和時間
- calendar:日歷相關的模塊,如:處理年歷/月歷
time模塊介紹
說明:time模塊主要講解如下內容:
- 1.時間戳 --> 時間元組格式(time.struct_time) --> 日期字符串
- 2.日期字符串 --> 時間元組格式(time.struct_time) --> 時間戳
- 3.獲取當前時間的分鐘/秒
- 4.獲取整分鐘/整小時時間戳
1.時間戳 --> 時間元組格式(time.struct_time) --> 日期字符串
- 時間戳 --> 時間元組格式
time.localtime(timestamp) # 參數timestamp為秒級時間戳 - 例子:
time.strftime(format, p_tuple=None):format:格式化的日期樣式;p_tuple:時間元組
例子:time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)print time_format # 2019-01-30 11:48:07封裝成方法:def timestamp_format(timestamp): """ :brief 時間戳格式化 :param timestamp: 時間戳 :return: 格式化后的日期 """ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
2.日期字符串 --> 時間元組格式(time.struct_time) --> 時間戳
- 日期字符串 --> 時間元組
time.strptime(string, format) # string:日期字符串,format:該日期字符串對應的格式化格式 - 例子:
time.mktime(p_tuple):p_tuple:時間元組例子:time_tuple_to_timestamp = int(time.mktime(time_str_to_tuple))print time_tuple_to_timestamp # 結果:1548820087
- 封裝成方法
3.獲取當前時間的分鐘/秒
- 獲取當前時間戳
- 獲取當前時間的秒
- 獲取當前時間的分鐘
4.獲取整分鐘/整小時時間戳
- 思路:
先除以對應的進制值取整,得到舍棄余數部分的整數,然后再乘以對應的進制值
datetime模塊介紹
datetime模塊中常見的類:
- datetime.date:處理日期
- datetime.time:處理時間
- datetime.datetime:處理日期和時間
- datetime.timedelta:處理時間差
說明:datetime模塊主要講解如下內容
- 1.時間戳 --> datetime時間格式 --> 日期字符串
- 2.日期字符串 --> datetime時間格式 --> 時間元組格式(time.struct_time) --> 時間戳
- 3.時間差的使用,根據當前時間獲取前N天的時間
1.時間戳 --> datetime時間格式 --> 日期字符串
- 時間戳 --> datetime時間格式
datetime.datetime.fromtimestamp(timestamp) 參數timestamp:時間戳
- 例子
datetime.datetime.strftime(format) format:日期字符串對應的格式化格式例子:datetime_format = datetime_type.strftime("%Y/%m/%d %H:%M:%S")print datetime_format # 2019/01/30 16:44:01
2.日期字符串 --> datetime時間格式 --> 時間元組格式(time.struct_time) --> 時間戳
- 日期字符串 --> datetime時間格式
datetime.datetime.strptime(date_str, format) date_str:字符串日期 format:日期字符串對應的格式化格式 - 例子:
datetime.datetime.timetuple(): datetime轉換為時間元組例子:datetime_type_to_timestamp = int(time.mktime(datetime_type.timetuple()))print datetime_type_to_timestamp
3.時間差的使用,根據當前時間獲取前N天的時間
datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks) 參數說明:
- 例子:
calendar模塊介紹
說明:
這里介紹一下使用month(year, month)方法打印出某年某月下的月歷時間
- 例子:
總結
以上是生活随笔為你收集整理的c++获取当前时间戳_python开发:python时间模块的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cookie和session、web服务
- 下一篇: python问题解决方案_Python安