python: time模块常用

1. 常用今日转换, 字符串转换时间戳, 时间戳转换字符串

#!/usr/bin/env python
# -*- encoding: utf-8 -*-


import time
import datetime
from loguru import logger


# 当日或者当前时间 获取年月日字符串
# 写法1
today_ymd_str = time.strftime("%Y-%m-%d")
logger.info(f'当日或者当前时间 年月日 {today_ymd_str} 类型{type(today_ymd_str)}')
# 当日或者当前时间 年月日 2021-02-04 类型<class 'str'>

# 写法2
today_ymd_str = time.strftime("%Y-%m-%d", time.localtime(int(time.time())))
logger.info(f'当日或者当前时间 年月日 {today_ymd_str} 类型{type(today_ymd_str)}')
# 当日或者当前时间 年月日 2021-02-04 类型<class 'str'>

# 写法3
today_ymd_str = datetime.date.today()
logger.info(f'当日或者当前时间 年月日 {today_ymd_str} 类型{type(today_ymd_str)}')
# 当日或者当前时间 年月日 2021-02-04 类型<class 'datetime.date'>
# 需要加.strftime("%Y-%m-%d")

# 同理可得
today_ymd_str = time.strftime("%Y-%m-%d")
today_ymd_h_str = time.strftime("%Y-%m-%d %H")
today_ymd_hm_str = time.strftime("%Y-%m-%d %H:%M")
today_ymd_hms_str = time.strftime("%Y-%m-%d %H:%M:%S")
logger.info(f'当日或者当前时间 {today_ymd_str}/{today_ymd_h_str}/{today_ymd_hm_str}/{today_ymd_hms_str}')
# 当日或者当前时间 2021-02-04/2021-02-04 14/2021-02-04 14:34/2021-02-04 14:34:35


# 使用历史时间戳转换为字符串
time_stamp = 1612321160
today_ymd_str = time.strftime("%Y-%m-%d", time.localtime(int(time_stamp)))
today_ymd_h_str = time.strftime("%Y-%m-%d %H", time.localtime(int(time_stamp)))
today_ymd_hm_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(int(time_stamp)))
today_ymd_hms_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time_stamp)))
logger.info(f'年月日时分秒时间 {today_ymd_str}/{today_ymd_h_str}/{today_ymd_hm_str}/{today_ymd_hms_str}')
# 年月日时分秒时间 2021-02-03/2021-02-03 10/2021-02-03 10:59/2021-02-03 10:59:20


# 使用任意字符串转换为时间戳
time_str = '2020-09-25 10:20:21'
ymd_hms_stamp = int(time.mktime(time.strptime(time_str, '%Y-%m-%d %H:%M:%S')))
logger.info(f'年月日时分秒时间戳 {ymd_hms_stamp}')
# 年月日时分秒时间戳 1601000421

  

 

posted @ 2021-02-04 18:02  Adamanter  阅读(79)  评论(0)    收藏  举报