《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())
相关推荐
郑州光合科技余经理6 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
天才测试猿8 小时前
2026软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
码哥DFS8 小时前
二叉树的直径
开发语言·javascript·算法
paopaokaka_luck9 小时前
基于springboot3+vue3的企业考勤管理系统(部门树递归、Echarts图形化分析)
开发语言·spring boot·学习·echarts·mybatis·需求分析·代码规范
minglie19 小时前
zynq高频小数据量PS闭环 抖动时间的测量
学习
long3169 小时前
MySQL 学习练习(配套 01 入门资料)
数据库·学习·mysql
张小凡vip9 小时前
python--爬虫--成熟的爬虫框架Scrapy
爬虫·python·scrapy
Pluchon9 小时前
Java个人综合项目——萌部落社区V2.0
java·python·spring·spring cloud·postman·idea
梦雨生生10 小时前
java开发工具(学习第一天)
java·开发语言·学习
不瘦80斤不改名10 小时前
01-vibe-coding-起源与本质
人工智能·python