首页 > 编程语言 >python之常用标准库-时间

python之常用标准库-时间

时间:2024-01-26 15:36:37浏览次数:31  
标签:常用 struct python 26 datetime 标准 时间 time print

1.time

  • 时间戳:它代表了从格林尼治时间1970年01月01日00时00分00秒(即北京时间的1970年01月01日08时00分00秒)开始到现在经过的总秒数。

  • struct_time:用一个包含9个序列的元组组成(tm_year=2024, tm_mon=1, tm_mday=26, tm_hour=2, tm_min=49, tm_sec=56, tm_wday=4, tm_yday=26, tm_isdst=-1),参数通过tuple展示

  • 字符串时间:多种格式的字符串时间 2024-01-26 03:00:29;Fri Jan 26 03:00:28 2024

  •  

1.1.struct_time

  • 时间戳转struct_time 

            localtime(时间戳))--》返回+8h的struct_time,时间戳为空时,默认为当前时间

            gmtime(时间戳))--》返回utc的struct_time,时间戳为空时,默认返回utc的struct_time

  • 字符串转struct_time

        strptime('2024-01-26 11:44:45','%Y-%m-%d %H:%M:%S)--》返回字符串对应的struct_time

  • struct_time([2024,01,26,11,44,45,4,26,0]) --》自身赋值
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 # print(dir(time))
5 #structime
6 print(time.localtime())#将时间戳转为struct_time格式 +8小时
7 print(time.gmtime(1706234296))#将时间戳转为struct_time格式的UTC时间
8 print(time.strptime('2024-01-26 02:49:56','%Y-%m-%d %H:%M:%S'))#字符串转为指定格式struct_time
9 print(time.struct_time([2024,1,26,14,54,34,5,26,0]))#给struct_time赋值
View Code

1.2.时间戳

  • time()--》获取当前时间戳
  • mktime(stuple)--》将struct_time转为时间戳
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 print(time.mktime(time.gmtime(1706234296)))#将struct_time转为时间戳
5 print(time.time())#时间戳
View Code

1.3.字符串

  • strftime('%Y-%m-%s %H:%M:%S','时间戳')
  • ctime(时间戳)
  • asctime(tuple)
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 #字符串
5 print(time.asctime(time.gmtime()))#将struct_time转为字符串e.g. 'Sat Jun 06 16:26:11 1998'
6 print(time.ctime(1706234296))#将时间戳转为字符串e.g. 'Sat Jun 06 16:26:11 1998'
7 print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime()))#struct_time转为指定格式字符串
View Code

1.4.sleep

def sleep(seconds): # real signature unknown; restored from __doc__
"""
sleep(seconds)

Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
"""
pass
翻译:延迟给定的秒数执行,参数可以时浮点数
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 print(time.sleep(0.40))#延迟执行参数
View Code

1.5.process_time

def process_time(): # real signature unknown; restored from __doc__
"""
process_time() -> float

Process time for profiling: sum of the kernel and user-space CPU time.
"""
return 0.0
翻译:分析进程处理时间:包含内核和cpu
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 print(time.process_time())#用于分析进程时间浮点数
View Code

1.6.thread_time

def thread_time(): # real signature unknown; restored from __doc__
"""
thread_time() -> float

Thread time for profiling: sum of the kernel and user-space CPU time.
"""
return 0.0
翻译:分析线程处理时间:包含内核和cpu

2.datetime

2.1 datetime.datetime.now()

def now(cls, tz=None):
"Construct a datetime from time.time() and optional time zone info."
t = _time.time()
return cls.fromtimestamp(t, tz)
翻译:通过时间戳time.time()和一个可选时间区,构建一个日期;打印当前时间

2.2 datetime.date.fromtimestamp(时间戳)

def fromtimestamp(cls, t):
"Construct a date from a POSIX timestamp (like time.time())."
y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
return cls(y, m, d)
翻译:通过一个时间戳构建一个日期;打印当前日期 2024-01-26

2.3 datetime.datetime.fromtimestamp(时间戳)

def fromtimestamp(cls, t, tz=None):
"""Construct a datetime from a POSIX timestamp (like time.time()).

A timezone info object may be passed in as well.
"""
_check_tzinfo_arg(tz)

return cls._fromtimestamp(t, tz is not None, tz)
翻译:通过一个时间戳构建一个日期时间,打印日期时间如2024-01-26 11:26:32

2.4 datetime.datetime.now()+datetime.timedelta()

if sys.version_info >= (3, 6):
def __init__(self, days: float = ..., seconds: float = ..., microseconds: float = ...,
milliseconds: float = ..., minutes: float = ..., hours: float = ...,
weeks: float = ..., *, fold: int = ...) -> None: ...
翻译:就是在now基础上加减给定参数值(正数为加,负数为减)
1 #!/usr/bin/python
2 #常用模块学习
3 import time ,datetime
4 print(datetime.datetime.now())
5 print(datetime.date.fromtimestamp(1706234296)) #时间戳转日期
6 print(datetime.datetime.fromtimestamp(1706234296))#时间戳转日期时间格式
7 print(datetime.datetime.now()+datetime.timedelta(5))#当前时间加5天
8 print(datetime.datetime.now()+datetime.timedelta(-5))#当前时间减5天
9 print(datetime.datetime.now()+datetime.timedelta(days=-5,hours=3,minutes=30))#当前时间加3小时30分钟
View Code

 

 

标签:常用,struct,python,26,datetime,标准,时间,time,print
From: https://www.cnblogs.com/Little-Girl/p/17989513

相关文章

  • python 1
    importmathdeflcm(a,b):print('最大公约数math.gcd({},{})'.format(a,b),math.gcd(a,b))returna*b//math.gcd(a,b)deflcm_range(n):lcm_value=1foriinrange(2,n+1):lcm_value=lcm(lcm_value,i)returnl......
  • kafka常用命令
    mac本地安装kafkabrewinstallkafka启动zookeeper、kafkabrewservicesstartzookeeperbrewservicesstartkafka创建一个topickafka-topics--create--bootstrap-serverlocalhost:9092--replication-factor1--partitions3--topictest_1创建一个生产者produce......
  • 10款Python常用的开发工具
    https://zhuanlan.zhihu.com/p/6597008091IDLE:Python自带的IDE工具IDLE(IntegratedDevelopmentandLearningEnvironment),集成开发和学习环境,是Python的集成开发环境,纯Python下使用 Tkinter 编写的IDE。支持平台:Windows,macOS,Linux适合人群:初学者支持语言:Python下......
  • python中利用变量解压列表、元组、字符串、字典、文件对象、迭代器和生成器等序列
    一、如果知道序列中元素的个数,可以直接进行变量赋值。coords=(102,40)lon,lat=coordsprint(lon)print(lat)text="news"a,b,c,d=textprint(a)print(b)print(c)print(d)二、如果不知道序列中元素的个数,可以通过*变量名来代表多个元素的变量,无论序列是什......
  • 浅谈Python两大爬虫库——urllib库和requests库区别
    在Python中,网络爬虫是一个重要的应用领域。为了实现网络爬虫,Python提供了许多库来发送HTTP请求和处理响应。其中,urllib和requests是两个最常用的库。它们都能够帮助开发人员轻松地获取网页内容,但在使用方式、功能和效率上存在一些差异。本文将深入探讨这两个库的区别,帮助你更好地选......
  • 10 个杀手级的 Python 自动化脚本
    重复性任务总是耗时且无聊,想一想你想要一张一张地裁剪100张照片或FetchAPI、纠正拼写和语法等工作,所有这些任务都很耗时,为什么不自动化它们呢?在今天的文章中,我将与你分享10个Python自动化脚本。所以,请你把这篇文章放在你的收藏清单上,以备不时之需,在IT行业里,程序员的学习永......
  • 一篇文章带你搞懂Python中的继承和多态
    在面向对象编程中,继承和多态是两个核心概念。它们是面向对象编程的基石,允许我们构建更加复杂和可重用的代码。本文将通过理论与实践相结合的方式,深入探讨Python中的继承和多态,帮助你更好地理解这两个概念。一、继承1、什么是继承?继承是面向对象编程中的一个重要概念,它允许我们创建......
  • 简单记录一下如何安装python以及pycharm(图文教程)(可供福建专升本理工类同学使用)
    本教程主要给不懂计算机的或者刚刚开始学习python的同学(福建专升本理工类)&网友学习使用,基础操作,比较详细,其他问题等待补充!安装Python1.进入python官网(https://www.python.org/),选择导航栏中的Downloads,然后把鼠标移到windows(你目前使用的操作系统),点击downloadforwindows下面的p......
  • 达梦数据库常用sql
    自增模式自增模式当设置IDENTITY_INSERT为ON时,必须把需要插入的列名列出来,不然报错正确例子:SETIDENTITY_INSERT(表名)ONinsertintotable(id,name)value(1,名称)SETIDENTITY_INSERT(表名)OFF我的改为如下可以正常执行:setIDENTITY_INSERTdbo.t_scsoni......
  • 在PyCharm中运行Python的unit测试时,出现‘file‘ object has no attribute ‘getvalue
    https://blog.csdn.net/m0_46900715/article/details/129725053  ......