Python处理时间戳和时间计算等的脚本分享

 更新时间:2022年07月27日 15:55:37   作者:念槐聚  
这篇文章主要为大家整理总结了5个实用的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()))

到此这篇关于Python处理时间戳和时间计算等的脚本分享的文章就介绍到这了,更多相关Python 时间戳 时间计算内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python+VTK环境搭建及第一个简单程序代码

    python+VTK环境搭建及第一个简单程序代码

    这篇文章主要介绍了python+VTK环境搭建及第一个简单程序代码,简单介绍了vtk,然后分享了安装步骤,最后涉及一个简单的代码示例,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Python内置函数Type()函数一个有趣的用法

    Python内置函数Type()函数一个有趣的用法

    这篇文章主要介绍了Python内置函数Type()函数一个有趣的用法,本文讲解的是个人发现在的一个有趣的用法,注意这种写法会导致代码很难读,需要的朋友可以参考下
    2015-02-02
  • python suds访问webservice服务实现

    python suds访问webservice服务实现

    这篇文章主要介绍了python suds访问webservice服务实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2020-06-06
  • Python学习笔记之open()函数打开文件路径报错问题

    Python学习笔记之open()函数打开文件路径报错问题

    这篇文章主要介绍了Python学习笔记之open()函数打开文件路径报错问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • Python中向一个集合添加值的操作方法

    Python中向一个集合添加值的操作方法

    从数学上讲,集合是一个在逻辑上有联系的不同对象的集合,在Python中,集合是一个内置的数据类型,它是无索引的和不可变的,这篇文章主要介绍了Python中向一个集合添加值的操作方法,需要的朋友可以参考下
    2023-10-10
  • 基于python3实现倒叙字符串

    基于python3实现倒叙字符串

    这篇文章主要介绍了基于python3实现倒叙字符串,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • Python 中的多值传递、灵活参数与无名参数的使用技巧

    Python 中的多值传递、灵活参数与无名参数的使用技巧

    Python 是一门高度抽象且易于使用的编程语言,函数作为其核心特性之一,具有非常强大的灵活性和可扩展性,本篇文章将深入讲解 Python 函数中的多值传递、灵活参数以及无名参数的使用技巧,让你轻松解锁 Python 函数的魔力,感兴趣的朋友一起看看吧
    2025-04-04
  • Python 多继承中的一个诡异现象 既是 Father又是grandfather

    Python 多继承中的一个诡异现象 既是 Father又是grandfather

    我们知道,在面向对象编程里面,继承是一个很重要的概念。子类可以使用父类的方法和属性,接下来小编将用举例的方式为大家讲解Python 多继承中的一个诡异现象 其即是爸爸又是爷爷的奇葩现象,感兴趣的小伙伴可以看下面文章具体了解
    2021-09-09
  • Python用内置模块来构建REST服务与RPC服务实战

    Python用内置模块来构建REST服务与RPC服务实战

    这篇文章主要介绍了Python用内置模块来构建REST服务与RPC服务实战,python在网络方面封装一些内置模块,可以用很简洁的代码实现端到端的通信,比如HTTP、RPC服务,下文实战详情,需要的朋友可以参考一下
    2022-09-09
  • Python读写压缩文件的方法

    Python读写压缩文件的方法

    这篇文章主要介绍了Python读写压缩文件的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07

最新评论