Python 日期和時間

2021-08-07 17:34:18 字數 3743 閱讀 1090

python 程式能用很多方式處理日期和時間,轉換日期格式是乙個常見的功能。

python 提供了乙個 time 和 calendar 模組可以用於格式化日期和時間。

時間間隔是以秒為單位的浮點小數。

每個時間戳都以自從2023年1月1日午夜(曆元)經過了多長時間來表示。

python 的 time 模組下有很多函式可以轉換常見日期格式。如函式time.time()用於獲取當前時間戳, 如下例項:

#!/usr/bin/python

# -*- coding: utf-8 -*-

import time; # 引入time模組

ticks = time.time()

print "當前時間戳為:", ticks

以上例項輸出結果:

當前時間戳為: 1504448734.19
時間戳單位最適於做日期運算。但是2023年之前的日期就無法以此表示了。太遙遠的日期也不行,unix和windows只支援到2023年。

上述也就是struct_time元組。這種結構具有如下屬性:

從返回浮點數的時間輟方式向時間元組轉換,只要將浮點數傳遞給如localtime之類的函式。

#!/usr/bin/python

# -*- coding: utf-8 -*-

import time

localtime = time.localtime(time.time())

print "本地時間為 :", localtime

以上例項輸出結果:

本地時間為 : time.struct_time(tm_year=2017, tm_mon=9, tm_mday=3, tm_hour=23,
tm_min=10, tm_sec=46, tm_wday=6, tm_yday=246, tm_isdst=0)
你可以根據需求選取各種格式,但是最簡單的獲取可讀的時間模式的函式是asctime():

#!/usr/bin/python

# -*- coding: utf-8 -*-

import time

localtime = time.asctime( time.localtime(time.time()) )

print "本地時間為 :", localtime

以上例項輸出結果:

本地時間為 : sun sep 03 23:13:47 2017
我們可以使用 time 模組的 strftime 方法來格式化日期,:

time.strftime(format[, t])
#!/usr/bin/python

# -*- coding: utf-8 -*-

import time

# 格式化成2016-03-20 11:45:39形式

print time.strftime("%y-%m-%d %h:%m:%s", time.localtime())

# 格式化成sat mar 28 22:24:24 2016形式

print time.strftime("%a %b %d %h:%m:%s %y", time.localtime())

# 將格式字串轉換為時間戳

a = "sat mar 28 22:24:24 2016"

print time.mktime(time.strptime(a,"%a %b %d %h:%m:%s %y"))

以上例項輸出結果:

2017-09-03 23:17:18

sun sep 03 23:17:18 2017

1459175064.0

>>>

python中時間日期格式化符號:calendar模組有很廣泛的方法用來處理年曆和月曆,例如列印某月的月曆:

#!/usr/bin/python

# -*- coding: utf-8 -*-

import calendar

cal = calendar.month(2017, 9)

print "以下輸出2023年9月份的日曆:"

print cal;

以上例項輸出結果:

以下輸出2023年9月份的日曆:

september 2017

mo tu we th fr sa su

1 2 3

4 5 6 7 8 9 10

11 12 13 14 15 16 17

18 19 20 21 22 23 24

25 26 27 28 29 30

time 模組包含了以下內建函式,既有時間處理相的,也有轉換時間格式的:

time模組包含了以下2個非常重要的屬性:

此模組的函式都是日曆相關的,例如列印某月的字元月曆。

星期一是預設的每週第一天,星期天是預設的最後一天。更改設定需呼叫calendar.setfirstweekday()函式。模組包含了以下內建函式:

python日期和時間 Python日期和時間

python程式可以通過多種方式處理日期和時間。日期格式之間的轉換是電腦的常見煩惱。python的時間和日曆模組可以幫助跟蹤日期和時間。什麼是蜱 時間間隔是以秒為單位的浮點數。1970年1月1日上午12 00 時代 時間的特殊時刻表示。python中有乙個受歡迎的時間模組,它提供了處理時間的功能,並...

python 時間和日期

python 程式用很多方式處理時間和日期,轉換日期格式是乙個常見的功能。python提供了乙個time 和calendar 模組可以用於格式化日期和時間。時間間隔是以秒為單位的浮點小數。每個時間戳都以自從1970年1月1日午夜 曆元 經過了多長時間來表示。python的time模組下有很多函式可以...

python 日期和時間

python 的 time 模組下有很多函式可以轉換常見日期格式。如函式time.time 用於獲取當前時間戳,如下例項 usr bin python3 import time print 當前時間戳為 time.time python3 test.py 當前時間戳為 1545807691.5492...