time與datetime與時間格式轉化

2021-08-10 14:16:48 字數 2186 閱讀 1133

#time模組基本不用與取時間,取時間推進

import time

for i in xrange(3):

print i

time.sleep(1)

輸出結果會1秒列印乙個數字直到打完

0 1

21, 先導入datetime類

2, 通過datetime的now方法就獲得當前所需要的時間

3, datetime還是有好多方法的,可以獲取year, month,等,請通過dir()方法檢視

4, 此時我們獲得的now_time還是乙個datetime類,所以我們需用用strftime方法轉換成字串,strftime的引數就是最終需要字串的形式。

5, strftime需要便是時間的引數有很多,下面我們介紹一下最長用的一些引數:

格式引數:

%y 帶世紀部分的十制年份

%m 十進位制表示的月份

%d 十進位制表示的每月的第幾天

%h 24小時制的小時

%m 十時制表示的分鐘數

%s 十進位制的秒數

%c 標準時間,如:04/25/17 14:35:14 類似於這種形式

這幾個引數就是最常用到的我們用的時間

6,timedelta可以接收days和seconds兩個引數,正數代表幾天之前的,負數代表幾天之前的

例項:

from datetime import datetime, timedelta

now_time = datetime.now()

print (now_time)

#精確到秒的時間

new_time = now_time.strftime('%y-%m-%d %h:%m:%s')

print (new_time)

#標準時間

aa = now_time.strftime('%c')

print (aa)

#表示昨天

yesterday = now_time + timedelta(days=-1)

print (yesterday)

#精確到昨天的秒

y = yesterday.strftime('%y-%m-%d %h:%m:%s')

print (y)

#表示明天

tommorow = now_time + timedelta(days=+1)

print tommorow

2017-11-09 14:20:03.955000

2017-11-09 14:20:03

11/09/17 14:20:03

2017-11-08 14:20:03.955000

2017-11-08 14:20:03

2017-11-10 14:20:03.955000

時間的三種存在方式:時間物件,時間字串,時間戳

from datetime import datetime, timedelta

import time

#字串轉datetime

string = '2017-04-25 11:59:58'

time1 = datetime.strptime(string,'%y-%m-%d %h:%m:%s')

print (time1)

print (type(time1))

#datetime轉字串

time1_str = datetime.strftime(time1, '%y-%m-%d %h:%m:%s')

print(time1_str)

print(type(time1_str))

#時間戳轉時間物件,這裡用到的time模組是單獨import time

new_time = time.time()

print (new_time)

now_time =datetime.fromtimestamp(new_time)

print (now_time)

2017-04-25 11:59:58

type 『datetime.datetime』

2017-04-25 11:59:58

type 『str』

1510150491.54

2017-11-08 22:14:51.539000

一 time與datetime模組

import time 我們先以當前時間為準,讓大家快速認識三種形式的時間 print time.time 時間戳 1487130156.419527 print time.strftime y m d x 格式化的時間字串 2017 02 15 11 40 53 print time.localt...

模組之time與datetime

模組之time與datetime import time print time.clock print time.process time 測量處理器運算時間 print time.altzone 返回utc時間差,以秒計算 print time.asctime 返回時間格式 print time....

常用模組之time與datetime模組

time 時間三種表現形式 1.時間戳 秒數 2.結構化時間 一般是給機器看的 3.格式化時間 一般是給人看的 三種時間是可以相互轉換的 1.time.sleep 原地阻塞指定的秒數 2.time.time 獲取時間戳時間 strftime time.strftime y m d 年月日 h m s...