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.2 pytest输出毫秒级的日志

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库来获取某一个jenkis job的构建时间时,返回的是一个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

posted @ 2020-11-22 15:35  后来者2012  阅读(326)  评论(0编辑  收藏  举报