> For the complete documentation index, see [llms.txt](https://docs.xiwind-corp.com/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.xiwind-corp.com/tech/python-library/time-shi-jian.md).

# time 【時間】

## struct\_time

***

`gmtime()`、`localtime()` 和 `strptime()` 返回的時間值序列的類型。 它是一個 [named tuple](https://docs.python.org/zh-tw/3/library/collections.html#collections.namedtuple) interface 物件：可以透過索引和屬性名稱訪問值。存在以下值：

<table><thead><tr><th width="112" align="center">Index</th><th width="193.33333333333331">Attribute</th><th>Values</th></tr></thead><tbody><tr><td align="center">0</td><td><code>tm_year</code></td><td>any value</td></tr><tr><td align="center">1</td><td><code>tm_mon</code></td><td>range <code>[1, 12]</code></td></tr><tr><td align="center">2</td><td><code>tm_mday</code></td><td>range <code>[1, 31]</code></td></tr><tr><td align="center">3</td><td><code>tm_hour</code></td><td>range <code>[0, 23]</code></td></tr><tr><td align="center">4</td><td><code>tm_min</code></td><td>range <code>[0, 59]</code></td></tr><tr><td align="center">5</td><td><code>tm_sec</code></td><td>range <code>[0, 61]</code>， <code>60</code> 在表示閏秒的時間戳中有效。由於向後兼容，所以保留 <code>61</code>。</td></tr><tr><td align="center">6</td><td><code>tm_wday</code></td><td>range <code>[0, 6]</code></td></tr><tr><td align="center">7</td><td><code>tm_yday</code></td><td>range <code>[1, 366]</code></td></tr><tr><td align="center">8</td><td><code>tm_isdst</code></td><td><code>0</code>, <code>1</code> or <code>-1</code>; <code>-1</code> 表示由 library 自動確定 DST (Daylight Saving Time)。</td></tr><tr><td align="center">N/A</td><td><code>tm_zone</code></td><td>時區名稱的縮寫</td></tr><tr><td align="center">N/A</td><td><code>tm_gmtoff</code></td><td>UTC offsets (seconds)</td></tr></tbody></table>

{% hint style="info" %}
**當長度不正確的 Tuple 或錯誤類型，傳遞給需要 struct\_time 的函數時，會引發 TypeError。**
{% endhint %}

### asctime(), ctime()

***

`asctime([t])` 將 `struct_time` 物件，轉換為表示本地的時間和日期。 如果您沒有提供 `t`，它將使用 `localtime()` 返回的本地的當前時間。

`ctime([secs])` 將 Epoch ，轉換為當前的時間和日期。如果未提供 `secs` 或 `secs=None` ，則使用 `time()` 返回的當前時間。 `ctime(secs)` 相當於 `asctime(localtime(secs))`。

{% hint style="info" %}
**紀元 (Epoch)。**

表示自 1970 年 1 月 1 日 00:00:00 UTC 以來經過的總秒數 (浮點數)。這是許多系統中存儲時間的常用方法，因為它很簡單 (只是一個數字)並且可以高精度地表示任何日期和時間。
{% endhint %}

{% hint style="info" %}
**浮點數 (float)。**

`float` 所能表示的最大值約為 1.8e308，最小值約為 2.2e-308。因此，Epoch 的最大值將約為 1.8e308 秒，即約 584 年 (即西元2554年)。
{% endhint %}

{% code title="PYTHON" %}

```python
'''asctime()'''
import time

# Get Current time
print(time.asctime())

# =========================================================
# Get time in seconds since the epoch
seconds = time.time()

# Convert to struct_time
time_struct = time.localtime(seconds)

# Convert to a string
time_str = time.asctime(time_struct)
print(time_str)

# =========================================================
# July 20, 1969, 20:17 UTC, when man first landed on the moon
timestamp = 14182900

# Convert to a struct_time in UTC
time_struct = time.gmtime(timestamp)

# Convert to a String
print(time.asctime(time_struct))
```

{% endcode %}

**執行結果：**

```TXT
Fri Jul  7 19:03:15 2023
Fri Jul  7 19:03:15 2023
Sun Jun 14 03:41:40 1970
```

{% code title="PYTHON" %}

```python
'''ctime()'''
mport time

# Gives current time
print(time.ctime())

# July 20, 1969, 20:17 UTC, when man first landed on the moon
timestamp = 14182900
print(time.ctime(timestamp))
```

{% endcode %}

**執行結果：**

```TXT
Output: Fri Jul  7 17:13:47 2023
Output: Sun Jun 14 03:41:40 1970
```

### gmtime(), localtime(), mktime()

***

`gmtime([secs])` 將 Epoch ，轉換為 UTC (Coordinated Universal Time) 格式的 `struct_time` 物件。如果未提供 `secs`，它將返回 UTC 時間。

`localtime([secs])` 與 `gmtime()` 類似，但轉換為本地時間。

`mktime(t)` 是 `localtime()` 的反函數。參數 `t` 是 struct\_time 或完整的 9-Tuple。它返回一個浮點數，以與 `time()` 兼容。

{% code title="PYTHON" %}

```python
import time

# 【gmtime()】
# Getting current time
utc_time = time.gmtime()
print(utc_time)

# Formatting the time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", utc_time)
print(formatted_time)

# =========================================================
# 【localtime()】
# Getting local time
local_time = time.localtime()
print(local_time)

# Formatting the time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted_time)
```

{% endcode %}

**執行結果：**

```TXT
time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=11, tm_min=11, tm_sec=11, tm_wday=4, tm_yday=188, tm_isdst=0)
2023-07-07 11:11:11

time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=19, tm_min=11, tm_sec=11, tm_wday=4, tm_yday=188, tm_isdst=0)
2023-07-07 19:11:11
```

{% code title="PYTHON" %}

```python
'''mktime()'''
import time

# =========================================================
# 【Converting the current time to epoch time】

# Get the current time
now = time.localtime()

# convert struct_time to epoch time
epoch_time = time.mktime(now)
print("Epoch time:", epoch_time)

# =========================================================
# 【Converting a specific time to epoch time】

# Define a time tuple
time_tuple = (2023, 7, 7, 15, 30, 0, 4, 188, -1)  # July 7, 2023, 15:30:00

# convert the time tuple to epoch time
epoch_time = time.mktime(time_tuple)
print("Epoch time:", epoch_time)

# =========================================================
# 【Comparing two dates】

# Define two time tuples
time_tuple1 = (2023, 7, 7, 15, 30, 0, 4, 188, -1)  # July 7, 2023, 15:30:00
time_tuple2 = (2023, 8, 7, 15, 30, 0, 1, 219, -1)  # August 7, 2023, 15:30:00

# Convert the time tuples to epoch time
epoch_time1 = time.mktime(time_tuple1)
epoch_time2 = time.mktime(time_tuple2)

# Compare the epoch times
print("Time difference in seconds:", epoch_time2 - epoch_time1)
```

{% endcode %}

**執行結果：**

```TXT
Epoch time: 1688727762.0
Epoch time: 1688715000.0
Time difference in seconds: 2678400.0
```

### strftime(), strptime()

***

`strftime(format[, t])` 將 `struct_time` 物件轉換為 `format` 指定的 String。 `format` 詳見：[strftime()](https://docs.python.org/3/library/time.html#time.strftime)。 如果未提供 `t`，則使用 `localtime()` 返回的當前時間。 `format` 必須是字符串。

`strptime(string[, format])` 根據 `format` 解析表示時間的 `string`，返回 `struct_time` 物件。

{% hint style="info" %}
**`strftime()` 是按照作業系統實現的，因此有時可以提供比原始文檔更多的指令。 但 `strptime()` 是獨立作業系統的，因此不一定支援所有未記錄的可用指令。**
{% endhint %}

{% hint style="info" %}
**`time` module 的 `struct_time` 不夠複雜，無法計算不同年份的日期之間的天數，為此我們可以使用使用 `datetime` module。**
{% endhint %}

{% code title="PYTHON" %}

```python
'''strptime()'''
import time

t = time.gmtime()
print(t) 

# =========================================================
# Extract specific values
t = time.localtime()
print(f"Year: {t.tm_year}")
print(f"Month: {t.tm_mon}")
print(f"Day of the week: {t.tm_wday}")

# Extract specific values (using indices)
print(f"Year: {t[0]}")
print(f"Month: {t[1]}")
print(f"Day of the week: {t[6]}")

# =========================================================
# Calculate the number of days between two dates
date1 = "2023-07-01"
date2 = "2023-07-07"

struct_time1 = time.strptime(date1, "%Y-%m-%d")
struct_time2 = time.strptime(date2, "%Y-%m-%d")

days_difference = struct_time2.tm_yday - struct_time1.tm_yday
print(f"The number of days between {date1} and {date2} is {days_difference}.")


# =========================================================
# Calculate the number of days between dates from different years
from datetime import datetime

date1 = "2023-07-01"
date2 = "2024-07-07"

# Convert strings to datetime objects
datetime1 = datetime.strptime(date1, "%Y-%m-%d")
datetime2 = datetime.strptime(date2, "%Y-%m-%d")

# Subtract datetimes and extract the number of days
days_difference = (datetime2 - datetime1).days
print(f"The number of days between {date1} and {date2} is {days_difference}.")
```

{% endcode %}

**執行結果：**

```TXT
time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=13, tm_min=55, tm_sec=10, tm_wday=4, tm_yday=188, tm_isdst=0)

Year: 2023
Month: 7
Day of the week: 4
Year: 2023
Month: 7
Day of the week: 4

The number of days between 2023-07-01 and 2023-07-07 is 6.

The number of days between 2023-07-01 and 2024-07-07 is 372.
```

\ <br>
