1. 程式人生 > 實用技巧 >Python中關於時間的使用場景

Python中關於時間的使用場景

一.顯示精確到毫秒的字串時間

1.1獲取當前時間,精確到毫秒

# -*- coding: utf-8 -*-
# @Time    : 2020/11/22 12:32
# @Author  : chinablue

import datetime

TIME_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
cur_time = datetime.datetime.now().strftime(TIME_FORMAT)

print(cur_time)

1.2pytest輸出毫秒級的日誌

1)編寫pytest配置檔案pytest.ini

[pytest]
log_cli = true
log_cli_level 
= INFO log_format = %(asctime)s.%(msecs)03d [%(levelname)-s] : %(message)s log_date_format = %Y-%m-%d %H:%M:%S

2)編寫用例檔案test1.py

# -*- coding: utf-8 -*-
# @Time    : 2020/11/22 14:14
# @Author  : chinablue
# @File    : test1.py

import pytest
import logging

logger = logging.getLogger(__name__)


class Test1():

    
def test_1(self): logger.debug("This is debug log.") logger.info("This is info log.") logger.warning("This is warning log.") logger.error("This is error log.") assert True if __name__ == '__main__': pytest.main(["test1.py"])

3)執行用例檔案test1.py

============================= test session starts =============================
platform win32 
-- Python 3.6.8rc1, pytest-6.1.2, py-1.9.0, pluggy-0.13.1 rootdir: D:\workspace_python\web_login, configfile: pytest.ini plugins: allure-pytest-2.8.18, repeat-0.8.0 collected 1 item test1.py::Test1::test_1 -------------------------------- live log call -------------------------------- 2020-11-22 14:15:59.432 [INFO] : This is info log. 2020-11-22 14:15:59.433 [WARNING] : This is warning log. 2020-11-22 14:15:59.433 [ERROR] : This is error log. PASSED [100%] ============================== 1 passed in 0.01s ==============================

從執行結果可以看出,此時輸出的log資訊中已顯示出毫秒資訊(即在pytest.ini中的log_format欄位中指定msecs變數)

二.字串時間和時間戳的相互轉化

2.1獲取當前的時間戳

# -*- coding: utf-8 -*-
# @Time    : 2020/11/13 17:13
# @Author  : chinablue

import time

# 獲取[秒級]時間戳
print(f"獲取當前時間戳(秒級):{int(time.time())}")
# 獲取[毫秒級]時間戳
print(f"獲取當前時間戳(毫秒級):{int(time.time() * 1000)}")
# 獲取[微秒級]時間戳
print(f"獲取當前時間戳(微秒級):{int(time.time() * 1000 * 1000)}")

2.2將秒級時間戳轉換為字串時間

# -*- coding: utf-8 -*-
# @Time    : 2020/11/13 17:13
# @Author  : chinablue

import time

timestamp = 1606028234
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

local_time = time.localtime(timestamp)
time_string = time.strftime(TIME_FORMAT, local_time)

print(time_string)

2.3將字串時間轉換為時間戳

# -*- coding: utf-8 -*-
# @Time    : 2020/11/13 17:13
# @Author  : chinablue

import time

time_string = "2020-11-22 14:57:14"
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

t = time.strptime(time_string, TIME_FORMAT)
timestamp = int(time.mktime(t))

print(timestamp)

三.將UTC時間轉換為北京時間

在python中使用jenkinsapi庫來獲取某一個jenkisjob的構建時間時,返回的是一個UTC時間(形如:2020-11-12 03:44:55+00:00)

此時,我們期望將這個UTC時間轉換為北京時間

# -*- coding: utf-8 -*-
# @Time    : 2020/11/13 17:13
# @Author  : chinablue

import datetime
from pytz import timezone

utc_str_time = "2020-11-12 03:44:55+00:00"

n_time = datetime.datetime.strptime(utc_str_time, '%Y-%m-%d %H:%M:%S+00:00')
utctime = datetime.datetime(n_time.year, n_time.month, n_time.day, n_time.hour, n_time.minute, n_time.second, tzinfo=timezone('UTC'))
beijing_time_raw = utctime.astimezone(timezone('Asia/Shanghai'))
beijing_time = beijing_time_raw.strftime("%Y-%m-%d %H:%M:%S")

print(beijing_time)

注意事項:

1)pytz模組需要安裝:pip install pytz