《0基础》学习Python——第十一讲__时间函数

一、时间函数是Python中的内置函数和模块,用于处理日期和时间相关的操作。以下是常用的时间函数的种类和用法:

1、time.time():返回当前时间的时间戳。

时间戳(timestamp)是一种表示日期和时间的方式,它是一个浮点数或整数,表示从某个特定的固定时间点(通常是1970年1月1日零点,也称为UNIX纪元)开始经过的秒数或毫秒数。在计算机编程中,时间戳常用于记录事件的发生时间、进行时间计算和比较等操作。

python 复制代码
import time

timestamp = time.time()
print(timestamp)

2、time.gtime():获取当前时间戳对应的struct_time对象

python 复制代码
import time
print(time.gmtime())
#其输出结果为:time.struct_time(tm_year=2024, tm_mon=7, tm_mday=15, tm_hour=13, tm_min=56, tm_sec=10, tm_wday=0, tm_yday=197, tm_isdst=0)

3、time.localtime()

python 复制代码
import time
print(time.localtime())
#打印结果为:time.struct_time(tm_year=2024, tm_mon=7, tm_mday=15, tm_hour=21, tm_min=57, tm_sec=32, tm_wday=0, tm_yday=197, tm_isdst=0)

tm_year:年份、tm_mon:月份、tm_mday:日期、tm_hour:小时、tim_sec:秒、tm_wday:星期、tm_yday:该年第几天、tm_isday:夏令时

4、time.ctime() :获取当前时间对应的易读结果

python 复制代码
import time
print(time.ctime())#输出结果为:Mon Jul 15 21:59:24 2024

5、time.sleep():暂停程序的执行一段时间。

python 复制代码
import time

print("Start")
time.sleep(2)  # 暂停2秒钟
print("End")

6、datetime.strftime(format):将日期和时间格式化为字符串

python 复制代码
from datetime import datetime
strs='今天是2024年7月15日,22时10分10秒'
str_time = datetime.strptime(strs, "今天是%Y年%m月%d日,%H时%M分%S秒")
strss = str_time.strftime("%d.%m.%Y  %H:%M:%S")
print(strss)
#其输出结果为15.07.2024  22:10:10

其中**%Y表示年,%m表示月,%d表示日,%H表示时,%M表示分,%S表示秒**

7、字符串转化成时间类型后,用str_time.year, str_time.month, str_time.day, str_time.hour, str_time.minute, str_time.second,str_time.microsecond 分别提取其中的数据,并分别表示为**年、月、日、时、分、秒、微秒,并且以整数的形式(int)**返回

python 复制代码
str_time = datetime.strptime(strs, "%Y-%m-%d %H:%M")
print(str_time.year, str_time.month, str_time.day, str_time.hour, str_time.minute, str_time.second,str_time.microsecond)

8、datetime.now(): 返回当前的日期和时间

python 复制代码
import datetime

current_datetime = datetime.datetime.now()
print(current_datetime)

其输出结果为:

9、datetime.strptime(string, format):将字符串解析为时间对象。

python 复制代码
import datetime

date_string = "2021-01-01"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(date_object)  #输出为2021-01-01 00:00:00
                 

10、str _time. timestamp :返回当前时间的时间戳,str_time为时间类型

python 复制代码
from datetime import datetime
strs='今天是2024年7月15日,22时10分10秒'
str_time = datetime.strptime(strs, "今天是%Y年%m月%d日,%H时%M分%S秒")
print(str_time.timestamp())
相关推荐
TF男孩7 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在12 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP14 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805120 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下20 小时前
最终的信号类
开发语言·c++·算法
c8i20 小时前
python中类的基本结构、特殊属性于MRO理解
python
echoarts20 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin050620 小时前
【ESP32-CAM】HELLO WORLD
python
2303_Alpha21 小时前
SpringBoot
笔记·学习
Aomnitrix21 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式