Python3日期和時間

Python程式可以通過多種方式來處理日期和時間。日期格式之間的轉換是計算機的一個共同核心。Python的時間和日曆模組能夠幫助我們跟蹤的日期和時間。

範例

```#!/usr/bin/python3
import time;  # This is required to include time module.

ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)```

`Number of ticks since 12:00am, January 1, 1970: 1455508609.34375 `

什麼是TimeTuple？

0 4-digit year 2016
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61 (60 or 61 are leap-seconds)
6 Day of Week 0 to 6 (0 is Monday)
7 Day of year 1 to 366 (Julian day)
8 Daylight savings -1, 0, 1, -1 means library determines DST

`>>> print (time.localtime())`

`time.struct_time(tm_year=2016, tm_mon=3, tm_mday=15, tm_hour=9, tm_min=29, tm_sec=2, tm_wday=0, tm_yday=46, tm_isdst=0)`

0 tm_year 2016
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap-seconds)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday 1 to 366 (Julian day)
8 tm_isdst -1, 0, 1, -1 means library determines DST

獲取當前時間

```#!/usr/bin/python3
import time

localtime = time.localtime(time.time())
print ("Local current time :", localtime)```

`Local current time : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=9, tm_min=29, tm_sec=2, tm_wday=0, tm_yday=46, tm_isdst=0)`

獲取格式化時間

```#!/usr/bin/python3
import time

localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)```

`Local current time : Mon Feb 15 09:34:03 2016`

獲取一個月份的日曆

```#!/usr/bin/python3
import calendar

cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)```

```Here is the calendar:
February 2016
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```

time模組

Python提供一個流行時間模組，為時間和表示之間轉換提供了相應函式。這裡是所有可用方法的列表 -

SN 函式及描述
1

2

3

4

5

6

7

8

9

10

11

12

SN

1 time.timezone

2 time.tzname

calendar模組

SN 方法及描述
1 calendar.calendar(year,w=2,l=1,c=6)

2 calendar.firstweekday( )

3 calendar.isleap(year)

4 calendar.leapdays(y1,y2)

5 calendar.month(year,month,w=2,l=1)

6 calendar.monthcalendar(year,month)

7 calendar.monthrange(year,month)

8 calendar.prcal(year,w=2,l=1,c=6)

9 calendar.prmonth(year,month,w=2,l=1)

10 calendar.setfirstweekday(weekday)

11 calendar.timegm(tupletime)

time.gmtime反轉：接受時間元組形式的時刻，並返回同一時刻作為自新紀元以來秒的浮點數

12 calendar.weekday(year,month,day)