python 常用的時間操作

2021-10-06 07:56:31 字數 1620 閱讀 6508

import time

import datetime

''' time '''

# 當前時間戳

print

(time.time())

# 1589898214.7195132

print

(int

(time.time())

)# 1589898422

print

(int

(time.time()*

1000))

# 1589898444940

# 當前格式化的時間

print

(time.strftime(

'%y-%m-%d %h:%m:%s'))

# 2020-05-19 22:28:06

print

(time.strftime(

'%y-%m-%d'))

# 2020-05-19

print

(time.strftime(

'%h:%m:%s'))

# 22:29:13

print

('*--*'*30

)''' datetime '''

# 獲取當前時間

print

(datetime.datetime.now())

# 2020-05-19 22:21:48.391236

print

(datetime.datetime.today())

# 2020-05-19 22:19:54.338640

# 今天日期 到天

print

(datetime.date.today())

# 2020-05-19

# 1個小時以前的時間 / 1天前的時間

now = datetime.datetime.now(

)print

(now - datetime.timedelta(hours=1)

)# 2020-05-19 21:33:38.238268

print

(now - datetime.timedelta(days=1)

)# 2020-05-18 22:34:17.714113

print

('*--*'*30

)''' 時間戳和字串的轉換 '''

# 轉時間戳

str_time =

'2020-05-18 14:12:32'

print

(time.mktime(time.strptime(str_time,

'%y-%m-%d %h:%m:%s'))

)# 時間戳轉字串

ts =

1589782352

print

(time.strftime(

'%y-%m-%d'

, time.localtime(ts)))

# 2020-05-18

print

(time.strftime(

'%y-%m-%d %h:%m:%s'

, time.localtime(ts)))

# 2020-05-18 14:12:32

python 日期時間常用操作

關於python時間模組問題 當前時間時間戳 1312181113.31 print time.time 將字串轉成時間戳 ts 2011 08 01 14 15 40 b time.mktime time.strptime ts,y m d h m s print b 返回指定時間的時間戳使用mk...

python 時間戳常用操作

時間戳常用操作主要是兩個方向 1.某個地方拿到乙個時間格式的字串,需要轉成時間戳 2.某個地方拿到時間戳,需要轉成時間格式方便檢視 time和datatime兩大模組 datetime更勝一籌 相容毫秒資訊的處理 兩大函式 strptime string,format struct time p p...

Python 時間模組time常用操作

time模組 時間的獲取和轉換 time模組提供各種時間相關的功能 下面列舉一些常用的操作 獲取時間戳 timestamp time.time print 時間戳 timestamp 時間戳 1540985031.5 獲取當地時間 localtime time.localtime print 當地時...