時間模塊和時間工具

一、time模塊

三種格式
時間戳時間:浮點數 單位為秒
時間戳起始時間:
1970.1.1 0:0:0 英國倫敦時間
1970.1.1 8:0:0 我國(東8區)
結構化時間:元組(struct_time)
格式化時間:str數據類型的

?

1、常用方法

import timetime.sleep(secs)   推遲指定的時間運行,單位是秒for i in range(3):time.sleep(1)print(i)

?

2、表示時間的三種方式

時間戳(timestamp)、元組(struct_time)、格式化(str_time)的時間字符串1. 時間戳(timestamp) :通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。
我們運行“type(time.time())”,返回的是float類型。
print(time.time())  # 1536050072.5732844(1970年1月1日00:00:00到此刻運行time.time()的時間) 2. 結構化時間(struct_time) :struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一周中第幾天,一年中第幾天,夏令時)
struct_time = time.localtime()  # 我國的時間
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=16, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)
struct_time = time.gmtime()  # 倫敦的時間
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=8, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)3. 格式化時間(Format_string):
fmt1 =time.strftime('%H:%M:%S')   # 時分秒(全大寫)
fmt2 =time.strftime('%Y-%m-%d')   # 年月日(年可大寫可小寫,月日小寫)
fmt3 =time.strftime('%y-%m-%d')   # 年月日
fmt4 =time.strftime('%c')         # 本地相應的日期表示和時間表示print(fmt1)  # 16:49:03
print(fmt2)  # 2018-09-04
print(fmt3)  # 18-09-04
print(fmt4)  # Tue Sep  4 16:49:03 2018

?

3、幾種時間格式間的轉換

1. 轉換

Timestamp ---> struct_time: time.localtime(轉成我國的時間)、time.gmtime(轉成倫敦時間)
struct_time ---> Timestamp: time.mktime()

Format_string ---> struct_time: time.strptime()
struct_time ---> Format_string: time.strftime()

?

2. 例子

1. 把格式化時間2018年8月8日轉成時間戳時間
str_time = '2018-8-8'
struct_time = time.strptime(str_time,'%Y-%m-%d')
print(struct_time)  # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=220, tm_isdst=-1)
timestamp = time.mktime(struct_time)
print(timestamp)   # 1533657600.02. 把時間戳時間轉成格式化時間
timestamp = 1500000000
struct_time = time.localtime(timestamp)
str_time = time.strftime('%Y-%m-%d',struct_time)
print(str_time)   # 2017-07-143. 寫函數,計算本月1號的時間戳時間
通過我拿到的這個時間,能迅速的知道我現在所在時間的年 月
def get_timestamp():str_time = time.strftime('%Y-%m-1')struct_time = time.strptime(str_time,'%Y-%m-%d')timestamp = time.mktime(struct_time)return timestamp
ret = get_timestamp()
print(ret)

?

%y 兩位數的年份表示(00-99%Y 四位數的年份表示(0000-9999%m 月份(01-12%d 月內中的一天(0-31%H 24小時制小時數(0-23%I 12小時制小時數(01-12%M 分鐘數(00-59%S 秒(00-59%a 本地簡化星期名稱%A 本地完整星期名稱%b 本地簡化的月份名稱%B 本地完整的月份名稱%c 本地相應的日期表示和時間表示%j 年內的一天(001-366%p 本地A.M.或P.M.的等價符%U 一年中的星期數(00-53)星期天為星期的開始%w 星期(0-6),星期天為星期的開始%W 一年中的星期數(00-53)星期一為星期的開始%x 本地相應的日期表示%X 本地相應的時間表示%Z 當前時區的名稱%% %號本身
3. python中時間日期格式化符號

?

二、datetime模塊

1、dateime.date

import datetime1. datetime.date類型(年月日)
注意:datetime.date類型就是time模塊的結構化時間,只是它在內部把結構化時間的顯示格式化了再打印出來
datetime.date.today()
datetime.date(2018, 12, 21)2.根據給定的時間戮,返回一個date對象
datetime.date.fromtimestamp(timestamp)  # 返回一個date對象,與datetime.date.today()作用相同
datetime.date.fromtimestamp(1528345678)  # 2018-06-073.由date日期格式轉化為字符串格式
datetime.date.strftime(format)datetime.date.today().strftime('%Y-%m-%d')  # "2018-12-21"
注意:date類型沒有strptime

?

2、datetime.dateime

注意:datetime是繼承了date的類
1. datetime.datetime類型(年月日時分秒微妙時區)
datetime.datetime.today() 
datetime.datetime.now()datetime.datetime(2018,12, 21, 8, 12, 8, 603000)返回當前日期時間的日期部分
datetime.datetime.today().date()  # 2018-12-21
返回當前日期時間的時間部分
datetime.datetime.now().time()  # 15:19:16.2304492.根據給定的時間戮,返回一個datetime對象
datetime.datetime.fromtimestamp()  # 返回一個datetime對象,與datetime.datetime.today()作用相同
datetime.datetime.fromtimestamp(1528345678)  # 2018-06-07 12:27:583. 由日期格式轉化為字符串格式
datetime.datetime.strftime(format)
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # "2018-12-21 09:17:14"3.由字符串格式轉化為日期格式
datetime.datetime.strptime()
datetime.datetime.strptime('2018-12-21 11:01:27', '%Y-%m-%d %H:%M:%S')4. 結構化時間:元組
注意:這就是結構化時間初始的樣子
datetime.datetime.now().timetuple()
# time.struct_time(tm_year=2018, tm_mon=12, tm_mday=21, tm_hour=9, tm_min=18, tm_sec=1, tm_wday=4, tm_yday=355, tm_isdst=-1)

?

3、datetime.timedelta

datetime.timedelta用于計算兩個日期之間的差值datetime.timedelta(weeks=1)  # 返回一個時間差,參數weeks,days,hours,minutes,[1 weeks=7 days],沒有years,months

例1:
import datetime
day7 = datetime.timedelta(days=7)  # 7天的時間時間隔  一年用52周表示 weeks=52
today = datetime.datetime.now()
# 7天之后的時間是什么
# today + 7
after_7 = today + day7
print(after_7, type(after_7))例2:
a=datetime.datetime.now()  # datetime.datetime(2018, 12, 21, 13, 15, 20, 871000)
b=datetime.datetime.now()  # datetime.datetime(2018, 12, 21, 13, 15, 29, 603000)print(b-a)  # datetime.timedelta(0, 0, 8, 732000)
print((b-a).seconds)  # 8
print((b-a).total_seconds())  # 8.732
或者
time1 = datetime.datetime(2018, 12, 20)
time2 = datetime.datetime(2017, 11, 12)"""計算天數差值"""
print((time1-time2).days)"""計算兩個日期之間相隔的秒數"""
print ((time1-time2).total_seconds())

?

4、datetime.time

time類有5個參數,datetime.time(hour,minute,second,microsecond,tzoninfo),返回08:29:301.datetime.time.replace()2.datetime.time.strftime(format):按照format格式返回時間3.datetime.time.tzname():返回時區名字4.datetime.time.utcoffset():返回時區的時間偏移量

?

三、時間工具dateutil

直接看例子感受時間工具的絕對時間relativedelta吧

from dateutil import relativedelta
import datetimenow = datetime.datetime.today()
print(now)  # 2018-12-21 15:47:31.005604# 下個月
next_month = now + relativedelta.relativedelta(months=1)
print(next_month)  # 2019-01-21 15:47:31.005604# 注意months和month的區別:
# months=1 表示在現在的日期基礎上加一個月的時間
# months=-1表示在現在的日期基礎上減一個月
# month=1 表示把現在的日期的月份設置為1月
# years, months, days, weeks, hours, minutes, seconds等也是跟對應的year,month,day,week...一樣
set_month = now + relativedelta.relativedelta(month=1)
print(set_month)  # 2018-01-21 15:47:31.005604# 注意與datetime.timedelta區別:
# datetime.timedelta沒有months和years參數
# 因此一個月用weeks=4表示,只能表示28天后,有偏差
next_month2 = now + datetime.timedelta(weeks=4)
print(next_month2)  # 2019-01-18 15:47:31.005604# 下個月加一周
next_month_week = now + relativedelta.relativedelta(months=1, weeks=1)
print(next_month_week)  # 2019-01-28 15:47:31.005604# 下個月加一周,上午10點
next_month_week_ten = now + relativedelta.relativedelta(months=1, weeks=1, hour=10)
print(next_month_week_ten)  # 2019-01-28 10:47:31.005604# 一年后的前一個月
next_year_premonth = now + relativedelta.relativedelta(years=1, months=-1)
print(next_year_premonth)  # 2019-11-21 15:47:31.005604

?

轉載于:https://www.cnblogs.com/Zzbj/p/10156501.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395663.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395663.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395663.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

redux擴展工具_用鴨子擴展您的Redux App

redux擴展工具How does your front-end application scale? How do you make sure that the code you’re writing is maintainable 6 months from now?您的前端應用程序如何擴展? 您如何確定您正在編寫的代碼從現在起6個月內可維護? Redux took the …

mac下源碼安裝redis

轉載:http://www.jianshu.com/p/6b5eca8d908b 下載安裝包 redis-3.0.7.tar.gz 官網地址:http://redis.io/download 解壓:tar -zvxf redis-3.0.7.tar.gz 將解壓后的文件夾放到 /usr/local目錄下 編譯測試:接下來在終端中切換到/usr/local/red…

代碼掃描工具測試覆蓋率工具

測試覆蓋率工具轉載于:https://www.cnblogs.com/vivian-test/p/5398289.html

php splqueue 5.5安裝,解析PHP標準庫SPL數據結構

SPL提供了雙向鏈表、堆棧、隊列、堆、降序堆、升序堆、優先級隊列、定長數組、對象容器SplQueue 隊列類進出異端&#xff0c;先進先出<?php $obj new SplQueue();//插入一個節點到top位置$obj->enqueue(1);$obj->enqueue(2);$obj->enqueue(3);/**SplQueue Object…

Beta階段敏捷沖刺總結

設想和目標 1. 我們的軟件要解決什么問題&#xff1f;是否定義得很清楚&#xff1f;是否對典型用戶和典型場景有清晰的描述&#xff1f; 在最開始的時候我們就是為了解決集美大學計算機工程學院網頁沒有搜索引擎的問題。因為沒有搜索引擎&#xff0c;在搜索內容時需要根據查找信…

c語言 二進制壓縮算法_使用C ++解釋的二進制搜索算法

c語言 二進制壓縮算法by Pablo E. Cortez由Pablo E.Cortez 使用C 解釋的二進制搜索算法 (Binary Search Algorithms Explained using C) Binary search is one of those algorithms that you’ll come across on every (good) introductory computer science class. It’s an …

【LATEX】個人版latex論文模板

以下是我的個人論文模板&#xff0c;運行環境為Xelatex(在線ide&#xff1a;Sharelatex.com) 鑒于本人常有插入程序的需求&#xff0c;故引用了lstlisting \RequirePackage{ifxetex} \ifxetex\documentclass[hyperref, UTF8, c5size, no-math, winfonts&#xff0c;a4paper]{ct…

初識virtual memory

一、先談幾個重要的東西 virtual memory是一個抽象概念&#xff0c;書上的原文是"an abstraction of main memory known as virtual memory"&#xff08;參考資料p776&#xff09;。那么什么是抽象概念。下面說說我個人對這個東西的理解。 所謂抽象概念是指抽象出來的…

java創建mysql驅動,JDBC之Java連接mysql實現增刪改查

使用軟件&#xff1a;mysql、eclipse鏈接步驟&#xff1a;1.注冊驅動2.創建一個連接對象3.寫sql語句4.執行sql語句并返回一個結果或者結果集5.關閉鏈接(一般就是connection、statement、setresult)這三個連接對象&#xff0c;關閉順序一般是(setresult ---> statement …

算法第五章作業

1.你對回溯算法的理解&#xff08;2分&#xff09; 回溯法&#xff08;探索與回溯法&#xff09;是一種選優搜索法&#xff0c;又稱為試探法&#xff0c;按選優條件向前搜索&#xff0c;以達到目標。但當探索到某一步時&#xff0c;發現原先選擇并不優或達不到目標&#xff0c;…

c++編碼風格指南_100%正確的編碼樣式指南

c編碼風格指南Here are three links worth your time:這是三個值得您花費時間的鏈接&#xff1a; The 100% correct coding style guide (4 minute read) 100&#xff05;正確的編碼樣式指南( 閱讀4分鐘 ) I wrote a programming language. Here’s how you can, too (10 minu…

xp開機黑屏故障分析

今天裝完xp系統之后&#xff0c;重啟開機發現竟然黑屏了&#xff0c;查資料發現有很多用戶在修改分辨率后&#xff0c;因顯示器不支持修改后的分辨率&#xff0c;會出現電腦黑屏的情況。分辨率調高了&#xff0c;超出了屏幕的范圍&#xff0c;肯定會黑屏&#xff0c;而且這個問…

應用程序圖標_如何制作完美的應用程序圖標

應用程序圖標by Nabeena Mali通過Nabeena Mali 如何制作完美的應用程序圖標 (How to Make the Perfect App Icon) With just 24 app icon slots on the first page of an iPhone home screen, or 28 if you have a fancy iPhone 7, creating the perfect app icon is a vital …

Luogu3702 SDOI2017 序列計數 矩陣DP

傳送門 不考慮質數的條件&#xff0c;可以考慮到一個很明顯的$DP:$設$f_{i,j}$表示選$i$個數&#xff0c;和$mod\ pj$的方案數&#xff0c;顯然是可以矩陣優化$DP$的。 而且轉移矩陣是循環矩陣&#xff0c;所以可以只用第一行的數字代替整個矩陣。當然了這道題$p \leq 100$矩陣…

java閏年的年份,Java案例-判斷給定年份是閏年

專注學子高考志愿填報&#xff0c;分享你所不知道信息。Java案例-判斷給定年份是閏年案例描述編寫程序&#xff0c;判斷給定的某個年份是否是閏年。閏年的判斷規則如下&#xff1a;(1)若某個年份能被4整除但不能被100整除&#xff0c;則是閏年。(2)若某個年份能被400整除&#…

通過path繪制點擊區域

通過path繪制點擊區域 效果 源碼 https://github.com/YouXianMing/Animations // // TapDrawImageView.h // TapDrawImageView // // Created by YouXianMing on 16/5/9. // Copyright © 2016年 YouXianMing. All rights reserved. //#import <UIKit/UIKit.h> #…

Raft與MongoDB復制集協議比較

在一文搞懂raft算法一文中&#xff0c;從raft論文出發&#xff0c;詳細介紹了raft的工作流程以及對特殊情況的處理。但算法、協議這種偏抽象的東西&#xff0c;僅僅看論文還是比較難以掌握的&#xff0c;需要看看在工業界的具體實現。本文關注MongoDB是如何在復制集中使用raft協…

db2 前滾會話

前滾會話 - CLP 示例ROLLFORWARD DATABASE 命令允許每次指定多個操作&#xff0c;各個操作由關鍵字 AND 隔開。例如&#xff0c;要前滾至日志末尾&#xff0c;然后完成&#xff0c;可將下列獨立的命令&#xff1a;db2 rollforward db sample to end of logsdb2 rollforward db …

史上最爛代碼_歷史上最大的代碼庫

史上最爛代碼Here’s a diagram of the biggest codebases in history, as measured by lines of code:這是歷史上最大的代碼庫的圖表&#xff0c;以代碼行來衡量&#xff1a; As you can see, Google has by far the largest codebase of all. And all 2 billion lines of co…

php添加jpeg,PHP-如何將JPEG圖像保存為漸進JPEG?

我具有以下將JPEG保存為漸進JPEG的功能.它已保存,但不是漸進式JPEG.這個對嗎 &#xff1f;function save($filename, $image_type IMAGETYPE_JPEG, $compression 75, $permissions null) {if ($image_type IMAGETYPE_JPEG) {imageinterlace($this->image, true); //conv…