Python 模塊 timedatetime

time & datetime 模塊

在平常的代碼中,我們常常需要與時間打交道。在Python中,與時間處理有關的模塊就包括:time,datetime,calendar(很少用,不講),下面分別來介紹。

在開始之前,首先要說明幾點:

一、在Python中,通常有這幾種方式來表示時間:

  1. 時間戳
  2. 格式化的時間字符串
  3. 元組(struct_time)共九個元素。由于Python的time模塊實現主要調用C庫,所以各個平臺可能有所不同。

二、幾個定義

UTC(Coordinated Universal Time,世界協調時)亦即格林威治天文時間,世界標準時間。在中國為UTC+8。DST(Daylight Saving Time)即夏令時。

時間戳(timestamp)的方式:通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”,返回的是float類型。

元組(struct_time)方式:struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。下面列出這種方式元組中的幾個元素:

索引(Index)      屬性(Attribute)              值(Values)
0                        tm_year(年)                   比如2011 
1                        tm_mon(月)                   1 - 12
2                        tm_mday(日)                 1 - 31
3                        tm_hour(時)                   0 - 23
4                        tm_min(分)                    0 - 59
5                        tm_sec(秒)                     0 - 61
6                        tm_wday(weekday)         0 - 6(0表示周一)
7                        tm_yday(一年中的第幾天)   1 - 366
8                        tm_isdst(是否是夏令時)       默認為-1

?

time模塊的方法

  • time.localtime([secs]):將一個時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準。
  • time.gmtime([secs]):和localtime()方法類似,gmtime()方法是將一個時間戳轉換為UTC時區(0時區)的struct_time。
  • time.time():返回當前時間的時間戳。
  • time.mktime(t):將一個struct_time轉化為時間戳。
  • time.sleep(secs):線程推遲指定的時間運行。單位為秒。
  • time.asctime([t]):把一個表示時間的元組或者struct_time表示為這種形式:'Sun Oct 1 12:04:38 2017'。如果沒有參數,將會將time.localtime()作為參數傳入。
  • time.ctime([secs]):把一個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。如果參數未給或者為None的時候,將會默認time.time()為參數。它的作用相當于time.asctime(time.localtime(secs))。
  • time.strftime(format[, t]):把一個代表時間的元組或者struct_time(如由time.localtime()和time.gmtime()返回)轉化為格式化的時間字符串。如果t未指定,將傳入time.localtime()。

? ? ? ? ? ? ? ?舉例:time.strftime("%Y-%m-%d %X", time.localtime()) #輸出'2017-10-01 12:14:23'

  • time.strptime(string[, format]):把一個格式化時間字符串轉化為struct_time。實際上它和strftime()是逆操作。

? ? ? ? ? ? ? 舉例:time.strptime('2017-10-3 17:54',"%Y-%m-%d %H:%M") #輸出 time.struct_time(tm_year=2017, tm_mon=10, tm_mday=3, tm_hour=17, tm_min=54, tm_sec=0, tm_wday=1, tm_yday=276, tm_isdst=-1)

?

?

?MeaningNotes
%aLocale’s abbreviated weekday name.?
%ALocale’s full weekday name.?
%bLocale’s abbreviated month name.?
%BLocale’s full month name.?
%cLocale’s appropriate date and time representation.?
%dDay of the month as a decimal number [01,31].?
%HHour (24-hour clock) as a decimal number [00,23].?
%IHour (12-hour clock) as a decimal number [01,12].?
%jDay of the year as a decimal number [001,366].?
%mMonth as a decimal number [01,12].?
%MMinute as a decimal number [00,59].?
%pLocale’s equivalent of either AM or PM.(1)
%SSecond as a decimal number [00,61].(2)
%UWeek number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.(3)
%wWeekday as a decimal number [0(Sunday),6].?
%WWeek number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.(3)
%xLocale’s appropriate date representation.?
%XLocale’s appropriate time representation.?
%yYear without century as a decimal number [00,99].?
%YYear with century as a decimal number.?
%zTime zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].?
%ZTime zone name (no characters if no time zone exists).?
?%%A literal?'%'character.

?


?

datetime模塊

相比于time模塊,datetime模塊的接口則更直觀、更容易調用

datetime模塊定義了下面這幾個類:

  • datetime.date:表示日期的類。常用的屬性有year, month, day;
  • datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond;
  • datetime.datetime:表示日期時間。
  • datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。
  • datetime.tzinfo:與時區有關的相關信息。(這里不詳細充分討論該類,感興趣的童鞋可以參考python手冊)

需要記住的方法僅以下幾個:

  1. d=datetime.datetime.now() 返回當前的datetime日期類型
d.timestamp(),d.today(), d.year,d.timetuple()等方法可以調用

2.datetime.date.fromtimestamp(322222) 把一個時間戳轉為datetime日期類型

3.時間運算

>>> datetime.datetime.now()datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)>>> datetime.datetime.now() + datetime.timedelta(4) #當前時間 +4天

datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)>>> datetime.datetime.now() + datetime.timedelta(hours=4) #當前時間+4小時

datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)

4.時間替換

>>> d.replace(year=2999,month=11,day=30)datetime.date(2999, 11, 30)

?

轉載于:https://www.cnblogs.com/devopsxin/p/9479833.html

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

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

相關文章

大數模板Java

import java.util.*; import java.math.BigInteger; public class Main{public static void main(String args[]){Scanner cinnew Scanner(System.in);BigInteger a,b;acin.nextBigInteger();bcin.nextBigInteger();System.out.println(a.add(b));//加法System.out.println(a.…

檸檬工會_工會經營者

檸檬工會Hey guys! This week we’ll be going over some ways to work with result sets in MySQL. These result sets are the outputs of your everyday queries, such as:大家好! 本周,我們將介紹一些在MySQL中處理結果集的方法。 這些結果集是您日常…

229. 求眾數 II

229. 求眾數 II 給定一個大小為 n 的整數數組,找出其中所有出現超過 ? n/3 ? 次的元素。 示例 1:輸入:[3,2,3] 輸出:[3]示例 2:輸入:nums [1] 輸出:[1]示例 3:輸入:…

寫給Java開發者看的JavaScript對象機制

幫助面向對象開發者理解關于JavaScript對象機制 本文是以一個熟悉OO語言的開發者視角,來解釋JavaScript中的對象。 對于不了解JavaScript 語言,尤其是習慣了OO語言的開發者來說,由于語法上些許的相似會讓人產生心理預期,JavaScrip…

Pythonic---------詳細講解

作者:半載流殤 鏈接:https://zhuanlan.zhihu.com/p/35219750 來源:知乎 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。Pythonic,簡言之就是以Python這門語言獨特的方式寫出既簡潔又優美的代碼…

大數據ab 測試_在真實數據上進行AB測試應用程序

大數據ab 測試Hello Everyone!大家好! I am back with another article about Data Science. In this article, I will write about what is A-B testing and how to use it on real life data-set to compare two advertisement methods.我回來了另一篇有關數據科…

492. 構造矩形

492. 構造矩形 作為一位web開發者, 懂得怎樣去規劃一個頁面的尺寸是很重要的。 現給定一個具體的矩形頁面面積,你的任務是設計一個長度為 L 和寬度為 W 且滿足以下要求的矩形的頁面。要求: 你設計的矩形頁面必須等于給定的目標面積。 寬度 …

node:爬蟲爬取網頁圖片

前言 周末自己在家閑著沒事,刷著微信,玩著手機,發現自己的微信頭像該換了,就去網上找了一下頭像,看著圖片,自己就想著作為一個碼農,可以把這些圖片都爬取下來做成一個微信小程序,說干…

如何更好的掌握一個知識點_如何成為一個更好的講故事的人3個關鍵點

如何更好的掌握一個知識點You’re launching a digital transformation initiative in the middle of the ongoing pandemic. You are pretty excited about this big-ticket investment, which has the potential to solve remote-work challenges that your organization fac…

centos 搭建jenkins+git+maven

gitmavenjenkins持續集成搭建發布人:[李源] 2017-12-08 04:33:37 一、搭建說明 系統:centos 6.5 jdk:1.8.0_144 jenkins:jenkins-2.93-1.1 git:git-2.9.0 maven:Maven 3.3.9 二、部署 2.1、jdk安裝 1)下…

638. 大禮包

638. 大禮包 在 LeetCode 商店中, 有 n 件在售的物品。每件物品都有對應的價格。然而,也有一些大禮包,每個大禮包以優惠的價格捆綁銷售一組物品。 給你一個整數數組 price 表示物品價格,其中 price[i] 是第 i 件物品的價格。另有…

記錄一次spark連接mysql遇到的問題

在使用spark連接mysql的過程中報錯了,錯誤如下 08:51:32.495 [main] ERROR - Error loading factory org.apache.calcite.jdbc.CalciteJdbc41Factory java.lang.NoClassDefFoundError: org/apache/calcite/linq4j/QueryProviderat java.lang.ClassLoader.defineCla…

什么事數據科學_如果您想進入數據科學,則必須知道的7件事

什么事數據科學No way. No freaking way to enter data science any time soon…That is exactly what I thought a year back.沒門。 很快就不會出現進入數據科學的怪異方式 ……這正是我一年前的想法。 A little bit about my data science story: I am a complete beginner…

python基礎03——數據類型string

1. 字符串介紹 在python中,引號中加了引號的字符都被認為是字符串。 1 namejim 2 address"beijing" 3 msg My name is Jim, I am 22 years old! 那單引號、雙引號、多引號有什么區別呢? 1) 單雙引號木有任何區別,部分情況 需要考慮…

Java基礎-基本數據類型

Java中常見的轉義字符: 某些字符前面加上\代表了一些特殊含義: \r :return 表示把光標定位到本行行首. \n :next 表示把光標定位到下一行同樣的位置. 單獨使用在某些平臺上會產生不同的效果.通常這兩個一起使用,即:\r\n. 表示換行. \t :tab鍵,長度上相當于四個或者是八個空格 …

季節性時間序列數據分析_如何指導時間序列數據的探索性數據分析

季節性時間序列數據分析為什么要進行探索性數據分析? (Why Exploratory Data Analysis?) You might have heard that before proceeding with a machine learning problem it is good to do en end-to-end analysis of the data by carrying a proper exploratory …

TortoiseGit上傳項目到GitHub

1. 簡介 gitHub是一個面向開源及私有軟件項目的托管平臺,因為只支持git 作為唯一的版本庫格式進行托管,故名gitHub。 2. 準備 2.1 安裝git:https://git-scm.com/downloads。無腦安裝 2.2 安裝TortoiseGit(小烏龜):https://torto…

496. 下一個更大元素 I

496. 下一個更大元素 I 給你兩個 沒有重復元素 的數組 nums1 和 nums2 ,其中nums1 是 nums2 的子集。 請你找出 nums1 中每個元素在 nums2 中的下一個比其大的值。 nums1 中數字 x 的下一個更大元素是指 x 在 nums2 中對應位置的右邊的第一個比 x 大的元素。如果…

利用PHP擴展Taint找出網站的潛在安全漏洞實踐

一、背景 筆者從接觸計算機后就對網絡安全一直比較感興趣,在做PHP開發后對WEB安全一直比較關注,2016時無意中發現Taint這個擴展,體驗之后發現確實好用;不過當時在查詢相關資料時候發現關注此擴展的人數并不多;最近因為…

美團騎手檢測出虛假定位_在虛假信息活動中檢測協調

美團騎手檢測出虛假定位Coordination is one of the central features of information operations and disinformation campaigns, which can be defined as concerted efforts to target people with false or misleading information, often with some strategic objective (…