天天看點

python處理時間戳、時間計算等的幾個小腳本

由于實際需要,簡要寫了個小腳本,并打包生成exe,供無網絡環境下使用

腳本1:顯示目前時間與時間戳,以及10分鐘後的時間與時間戳

# -*- coding: utf-8 -*- 
"""
Project: pyWorkspace
Creator: Administrator -haochuang
Create time: 2021-05-12 09:24
IDE: PyCharm
Introduction:

"""      
import time
import datetime


t=datetime.datetime.now()

#目前日期
t1 =t.strftime('%Y-%m-%d %H:%M:%S')
#轉為秒級時間戳
ts1=time.mktime(time.strptime(t1, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
end_time=int(str(ts1*1000).split(".")[0])


#10分鐘後
t2 = (t+datetime.timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S")
# t2=(t-datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
#轉為秒級時間戳
ts2=time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
start_time=int(str(ts2*1000).split(".")[0])

#print("\n","*"*30)
print("\n")
print("*"*30)
print("目前時間戳:")
print(start_time)
print("目前時間:")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts2)))
print("*"*30,"\n")

print("10分鐘後的時間戳:")
print(end_time)
print("10分鐘後的時間:")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts1)))

print("*"*30,"\n")      

腳本2:顯示目前時間與時間戳,以及10分鐘後的時間與時間戳,允許根據輸入的指定時間,生成多久之後的時間戳

# -*- coding: utf-8 -*- 
"""
Project: pyWorkspace
Creator: Administrator -haochuang
Create time: 2021-05-12 09:24
IDE: PyCharm
Introduction:

"""      
import time
import datetime


t=datetime.datetime.now()

#目前日期
t1 =t.strftime('%Y-%m-%d %H:%M:%S')
#轉為秒級時間戳
ts1=time.mktime(time.strptime(t1, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
end_time=int(str(ts1*1000).split(".")[0])


#10分鐘後
t2 = (t+datetime.timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S")
# t2=(t-datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
#轉為秒級時間戳
ts2=time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
start_time=int(str(ts2*1000).split(".")[0])

#print("\n","*"*30)
print("\n")
print("*"*30)
print("目前時間戳:")
print(start_time)
print("目前時間:")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts2)))
print("*"*30,"\n")

# 10分鐘後的時間戳
print("10 分鐘後的時間戳:")
print(end_time)
print("10 分鐘後的時間:")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts1)))
print("*"*30,"\n")

# 使用者自定義時間
time_user = input("需要多少分鐘後的時間戳(請輸入正确int類型數值):")
t3 = (t+datetime.timedelta(minutes=int(time_user))).strftime("%Y-%m-%d %H:%M:%S")
ts3=time.mktime(time.strptime(t3, '%Y-%m-%d %H:%M:%S'))
#轉為毫秒級
start_time=int(str(ts3*1000).split(".")[0])

print(time_user + " 分鐘後的時間戳:")
print(end_time)
print(time_user + " 分鐘後的時間:")
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts3)))
print("*"*30,"\n")      

腳本3:顯示部分時間與時間戳等

# -*- coding: utf-8 -*- 
"""
Project: pyWorkspace
Creator: Administrator -haochuang
Create time: 2021-05-12 09:24
IDE: PyCharm
Introduction:

"""
import time
import datetime
from datetime import timezone
from datetime import timedelta

# 顯示目前秒級時間戳與毫秒級時間戳、微秒級時間戳
t = time.time()
#print(t)  # 原始時間資料
#print(int(t))  # 秒級時間戳
#print(int(round(t * 1000)))  # 毫秒級時間戳
#print(int(round(t * 1000000)))  # 微秒級時間戳


# 顯示目前日期:
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 含微秒的日期時間,來源 比特量化
print("目前日期(s):     " + dt)
print("目前日期(ms):    " + dt_ms)


# 将日期轉為秒級時間戳
#dtt = '2018-01-01 10:40:30'
#dtts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
#ts_ms = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
t=datetime.datetime.now()
print("目前時間戳(s):    " + t)
print("目前時間戳(ms):   " + (int(round(t * 1000))))


# 國際标準時間
print("國際标準時間:    "+time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()))
# 本地時間
print("本地目前時間:    "+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

# 将目前日期轉為秒級時間戳
dt = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
dt_ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
print("目前時間:        " + dt)
print("目前時間戳:      " + dt_ts)

# 将擷取十分鐘後的秒級時間戳
#dt_10 = int((datetime.datetime.now()+datetime.timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S"))
#ts_10 = int(time.mktime(time.strptime(dt_10, "%Y-%m-%d %H:%M:%S")))
after10 = (datetime.datetime.now()+datetime.timedelta(minutes=10)).strftime("%Y-%m-%d %H:%M:%S")
after10_ts = int(time.mktime(time.strptime(t1,after10)))
print("10分鐘後的時間:   " + after10)
print("10分鐘後的時間戳: "      

腳本4:顯示部分時間與時間戳等

# -*- coding: utf-8 -*- 
"""
Project: pyWorkspace
Creator: Administrator -haochuang
Create time: 2021-05-12 09:08
IDE: PyCharm
Introduction:

"""

import datetime
import time

print('*'*30 +"擷取時間方式")
#擷取目前時間:Thu Nov 03 16:40:00 2016
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

#擷取目前時間:2016-11-03 16:40:00
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

#擷取年,月,日:2016-11-03
print(datetime.date.today())

#擷取目前時間:2016-11-03 16:43:14.550000
print(datetime.datetime.now())

#不加參數是00:00,參數days=1表示一天:1 day, 0:00:00
print(datetime.timedelta(days=1))

#擷取昨天日期:2016-11-02
nowtime=datetime.date.today()
oldtime=datetime.timedelta(days=1)
print(nowtime-oldtime)

#擷取昨天的精确日期
oldtime=datetime.timedelta(days=1)
print (datetime.datetime.now() - oldtime)

print ('*'*30 + 'python時間處理之time子產品')

import time
# 傳回時間戳
# print(time.time())

# 傳回目前時間
print(time.ctime())

# 傳回一天前的時間
print(time.ctime(time.time()-86400))

# 函數傳回time.struct_time類型的對象
time_obj = time.gmtime()
print(time_obj)
#結果:time.struct_time(tm_year=2016, tm_mon=7, tm_mday=27, tm_hour=8, tm_min=52, tm_sec=26, tm_wday=2, tm_yday=209, tm_isdst=0)
# 格式化輸出:
print(time_obj.tm_year,time_obj.tm_mon,time_obj.tm_mday)

print("{year}-{month}".format(year=time_obj.tm_year,month=time_obj.tm_mon))

# 以time.struct_time類型,列印本地時間
print(time.localtime())

# 轉換成時間戳
time_obj = time.gmtime()
print(time.mktime(time_obj))

# 延時2秒
time.sleep(2)

# 列印UTC,世界标準時間,北京時區是東八區,領先UTC八個小時
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))

# 本地時間
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

# 把time.struct_time類型時間,轉換成時間戳
tm = time.strptime("2016-05-6 15:06:33","%Y-%m-%d %H:%M:%S")
print(tm)
print(time.mktime(tm))


print ('*'*30 + '3-python時間處理之datetime子產品')

import datetime

# 列印目前,年,月,日
print(datetime.date.today())

# 列印目前時間,精确到微秒
current_time = datetime.datetime.now()
print(current_time)

# 轉成time.struct_time格式時間
current_time = datetime.datetime.now()
print(current_time.timetuple())

# 加十天
print(datetime.datetime.now() +datetime.timedelta(days=10))
# 減十天
print(datetime.datetime.now() +datetime.timedelta(days=-10))
# 減十個小時
print(datetime.datetime.now() +datetime.timedelta(hours=-10))
# 加120s
print(datetime.datetime.now() +datetime.timedelta(seconds=120))

# 替換成指定的時間
cr_time = datetime.datetime.now()
print(cr_time.replace(2014,9,12))
# 結果:2014-09-12 17:28:17.522893

# 格式化輸出
print(datetime.datetime.strptime("21/11/06 16:30","%d/%m/%y %H:%M"))

# 替換成指定時間後,類型是<class 'datetime.datetime'>
current_time = datetime.datetime.now()
time_obj = current_time.replace(2015,5)
print(time_obj,type(time_obj))
# 結果:2015-05-27 17:34:13.350245 <class 'datetime.datetime'>

# 對比時間大小,取指定時間範圍使用
current_time = datetime.datetime.now()
time_obj = current_time.replace(2015,5)
print(current_time>time_obj)

import datetime
def getYesterday():
    today=datetime.date.today()
    oneday=datetime.timedelta(days=1)
    yesterday=today-oneday
    return yesterday

# 輸出
print(getYesterday())      

腳本5:關于時間戳處理

# -*- coding: utf-8 -*- 
"""
Project: pyWorkspace
Creator: Administrator -haochuang
Create time: 2021-05-12 09:24
IDE: PyCharm
Introduction:

"""
import time
import datetime
from datetime import timezone
from datetime import timedelta

# 顯示目前秒級時間戳與毫秒級時間戳、微秒級時間戳
t = time.time()
print(t)  # 原始時間資料
print(int(t))  # 秒級時間戳
print(int(round(t * 1000)))  # 毫秒級時間戳
print(int(round(t * 1000000)))  # 微秒級時間戳


# 顯示目前日期:
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # 含微秒的日期時間,來源 比特量化
print(dt)
print(dt_ms)


# 将日期轉為秒級時間戳
dt = '2018-01-01 10:40:30'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
print(ts)


# 将秒級時間戳轉為日期
ts = 1515774430
dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
print(dt)

# 時區轉換
# 顯示UTC時間
utc_now = datetime.datetime.utcnow()
print(utc_now)
# 世界标準時間
# utc_time = datetime(2019, 7, 30, 7, 50, 0)
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# 中原標準時間UTC+8
# cst_time =utc_time.astimezone(timezone(timedelta(hours=-8))).strftime("%Y-%m-%d %H:%M:%S")

# 國際标準時間
print("國際标準時間:"+time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()))
# 本地時間
print("本地時間:"+time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))      

待續...

贈人玫瑰

手留餘香

我們曾如此渴望命運的波瀾,到最後才發現:人生最曼妙的風景,竟是内心的淡定與從容……我們曾如此期盼外界的認可,到最後才知道:世界是自己的,與他人毫無關系!-楊绛先生