Python---time和datatime模块详解及使用

        时间无疑是生活各个方面中最关键的因素之一,因此,记录和跟踪时间变得非常重要。在 Python 中,可以通过其内置库跟踪日期和时间。今天我们来介绍关于 Python 中的日期和时间,一起来了解如何使用timedatetime模块查找和修改日期和时间。

一、Python 中处理日期和时间的模块

        Python 提供了timedatetime模块,可以帮助我们轻松获取和修改日期和时间,下面让我们来逐一了解一下。

time 模块

        该模块包括使用时间执行各种操作所需的所有与时间相关的功能,它还允许我们访问多种用途所需的时钟类型。

内置函数:

        请看下表,它描述了时间模块的一些重要内置功能。

functionDescription
time()返回自epoch以来经过的秒数
ctime()以经过的秒数作为参数,返回当前日期和时间
sleep()在给定的持续时间内停止线程的执行
time.struct_time Class函数要么将此类作为参数,要么将其作为输出返回
localtime()以自epoch以来经过的秒数作为参数,并以时间形式返回日期和时间。struct_time格式
gmtime()与localtime()类似,返回时间。UTC格式的struct_time
mktime()ocaltime()的倒数。获取包含9个参数的元组,并返回自epoch pas输出以来经过的秒数
asctime()获取包含9个参数的元组,并返回表示相同参数的字符串
strftime()获取包含9个参数的元组,并根据使用的格式代码返回表示相同参数的字符串
strptime()分析字符串并及时返回。struct_time格式

代码格式化:

        在用示例解释每个函数之前,先看一下所有合法的格式化代码的方式:

CodeDescriptionExample
%aWeekday (short version)Mon
%AWeekday (full version)Monday
%bMonth (short version)Aug
%BMonth (full version)August
%cLocal date and time versionTue Aug 23 1:31:40 2019
%dDepicts the day of the month (01-31)07
%fMicroseconds000000-999999
%HHour (00-23)15
%IHour (00-11)3
%jDay of the year235
%mMonth Number (01-12)07
%MMinutes (00-59)44
%pAM / PMAM
%SSeconds (00-59)23
%UWeek number of the year starting from Sunday (00-53)12
%wWeekday number of the weekMonday (1)
%WWeek number of the year starting from Monday (00-53)34
%xLocal date06/07/22
%XLocal time12:30:45
%yYear (short version)22
%YYear (full version)2022
%zUTC offset+0100
%ZTimezoneCST
%%% Character%

        struct_time 类具有以下属性:

AttributeValue
tm_year0000, .., 2019, …, 9999
tm_mon1-12
tm_mday1-31
tm_hour0-23
tm_min0-59
tm_sec0-61
tm_wday0-6  (Monday is 0)
tm_yday1-366
tm_isdst0, 1, -1    (daylight savings time, -1 when unknown)

现在让我们看几个 time 模块的例子

使用time模块查找日期和时间

        使用上表中描述的内置函数和格式化代码,可以在 Python 中轻松获取日期和时间。

import time
#time
a=time.time()           #total seconds since epoch
print("Seconds since epoch :",a,end='n----------n')
#ctime
print("Current date and time:")
print(time.ctime(a),end='n----------n') 
#sleep
time.sleep(1)     #execution will be delayed by one second
#localtime
print("Local time :")
print(time.localtime(a),end='n----------n')
#gmtime
print("Local time in UTC format :")
print(time.gmtime(a),end='n-----------n')
#mktime
b=(2019,8,6,10,40,34,1,218,0)
print("Current Time in seconds :")
print( time.mktime(b),end='n----------n')
#asctime
print("Current Time in local format :")
print( time.asctime(b),end='n----------n')
#strftime
c = time.localtime() # get struct_time
d = time.strftime("%m/%d/%Y, %H:%M:%S", c)
print("String representing date and time:")
print(d,end='n----------n')
#strptime
print("time.strptime parses string and returns it in struct_time format :n")
e = "06 AUGUST, 2019"
f = time.strptime(e, "%d %B, %Y")
print(f)

Output:

Seconds since epoch : 1565070251.7134922
———-
Current date and time:
Tue Aug 6 11:14:11 2019
———-
Local time :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=11, tm_min=14, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———-
Local time in UTC format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=5, tm_min=44, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———–
Current Time in seconds :
1565068234.0
———-
Current Time in local format :
Tue Aug 6 10:40:34 2019
———-
String representing date and time:
08/06/2019, 11:14:12
———-
time.strptime parses string and returns it in struct_time format :

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)

datetime 模块

        与time模块类似,datetime模块包含处理日期和时间所必需的所有方法。

内置功能:

下表介绍了本模块中的一些重要功能:

functionDescription
datetime()datetime 的构造函数
datetime.today()返回当前本地日期和时间
datetime.now()返回当前本地日期和时间
date()以年、月、日为参数,创建相应的日期
time()以小时、分钟、秒、微秒和tzinfo作为参数,并创建相应的日期
date.fromtimestamp()转换秒数以返回相应的日期和时间
timedelta()它是不同日期或时间之间的差异(持续时间)

使用 datetime 查找日期和时间

现在,让我们尝试实现这些函数,以使用datetime模块在 Python 中查找日期和时间。

import datetime
#datetime constructor
print("Datetime constructor:n")
print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n')
 
#today
print("The current date and time using today :n")
print(datetime.datetime.today(),end='n----------n')
 
#now
print("The current date and time using today :n")
print(datetime.datetime.now(),end='n----------n')
 
#date
print("Setting date :n")
print(datetime.date(2019,11,7),end='n----------n')
  
#time
print("Setting time :n")
print(datetime.time(6,30,23),end='n----------n')
 
#date.fromtimestamp
print("Converting seconds to date and time:n")
print(datetime.date.fromtimestamp(23456789),end='n----------n')
 
#timedelta
b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b3=b2-b1
print(type(b3))
print("The resultant duration = ",b3,end='n----------n')
 
#attributes
a=datetime.datetime.now()   #1
print(a)
print("The year is :",a.year)
 
print("Hours :",a.hour)

Output:

Datetime constructor:

2019-05-03 08:45:30.000234
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
Setting date :

2019-11-07
———-
Setting time :

06:30:23
———-
Converting seconds to date and time:
1970-09-29
———-
<class ‘datetime.timedelta’>
The resultant duration = -27 days, 0:00:00
———-
2019-08-06 13:09:56.653694
The year is : 2019
Hours : 13

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Python datetime数据库包括一个datetime对象,它有时间、日期、时间戳和相关的函数可以操作时间和日期。它还有一些更高级的功能,可以比较两个日期/时间,计算时间增量和检查特定时间是否在指定的范围内。 ### 回答2: Pythondatatime库是Python标准库中的一个模块,用来处理日期和时间相关的操作。该库提供了多个类和函数,用于处理日期、时间和时间间隔的计算、转换和格式化。 datetime类是datatime库中最常用的类,用于表示时间和日期。它包括year、month、day、hour、minute、second、microsecond等属性,可以通过这些属性获取或设置具体的日期和时间。datetime类也实现了一系列的方法,如获取当前日期和时间、计算日期和时间的差值、判断某个日期是否为闰年等。 另外,datatime库还提供了其他类和函数,用于处理时间间隔、时区和日期时间的格式化输出。timedelta类用于表示时间间隔,例如计算两个日期之间的天数、小时数等。timezone类用于处理不同时区的时间计算。strftime函数用于将日期时间对象格式化为字符串,而strptime函数则用于将字符串解析为日期时间对象。 总的来说,datatime库提供了丰富的功能,使得开发者在Python中能够方便地处理日期和时间相关的操作。无论是计算时间差、格式化输出,还是处理不同时区的时间,都可以通过datatime库轻松实现。 ### 回答3: Python datetime模块Python标准库中的一个模块,用于处理日期和时间相关的操作。它提供了一些类和函数,可以方便地处理日期、时间、时间间隔、时间序列等数据。 datetime模块中包含一些重要的类,如datetime、date、timetimedelta。 1. datetime类:该类表示一个具体的日期和时间,包含年、月、日、小时、分钟、秒等信息。可以用于创建、操作和格式化日期时间。 2. date类:该类表示一个具体的日期,包含年、月、日信息。可以用于获取日期的各个部分,以及比较日期等操作。 3. time类:该类表示一个具体的时间,包含小时、分钟、秒、微秒等信息。可以用于获取时间的各个部分,以及比较时间等操作。 4. timedelta类:该类表示两个日期或时间之间的时间间隔。可以用于计算时间的差值,以及时间的加减操作。 此外,datetime模块还提供了一些常用的函数,如today()函数用于获取当前日期时间,strftime()函数用于将日期时间对象格式化为字符串,strptime()函数用于将字符串解析为日期时间对象等。 在数据库中,datetime类型可以用来存储和操作日期时间信息。可以将datetime对象插入到数据库中的datetime字段中,也可以从数据库中的datetime字段读取数据并将其转换为datetime对象。 总之,Python的datetime模块是用于处理日期和时间的强大工具,可以方便地进行日期时间的计算、格式化和数据库操作等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缓下脚步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值