Python 模块:处理日期和时间datetime
off999 2024-09-29 15:59 38 浏览 0 评论
Python 模块:处理日期和时间datetime
Python 是一种高级、通用、解释型编程语言,其构建考虑了简单性和可读性。通过各种简化语言的可用模块,Python 对初学者友好且易于使用;一个例子是 Python 模块,它帮助我们管理 Python 中日期和时间计算的复杂性。datetime
每个开发人员在使用日期和时间时遇到的一个主要问题是全球时区的差异问题。使用 Python 模块,您可以编写以分钟、小时、秒或毫秒为单位获取月份中的某天、星期几以及本地日期和时间的程序。datetime
Python 模块由五个主要类组成:、、、 和 。在本文中,我们将讨论这些类,并涵盖每个类的相关示例。datetimedatetimetzinfoDateTimetimedelta
先决条件
若要按照本文进行操作,需要以下内容:
- 对 Python 的基本了解
- 计算机上安装的最新版本的 Python
- 一个IDE,最好是PyCharm
让我们开始吧!
datetime模块类
Python 模块帮助我们处理与时间相关的事件,如年、月、周、天、小时、分钟、秒等。尽管最常用的类是 、、、 和 ,以获取 Python 日期时间模块中存在的其他元素,请运行以下代码:datetimeDateTimeDateTimeTzinfoTimedelta
import datetime
print(dir(datetime))datetime.class
该类使Python开发人员能够操作日期和时间。要在 Python 程序中使用该类,我们需要从模块导入它。让我们编写一个简单的 Python 程序来使用 Python 模块打印时间和日期:datetimedatetimedatetimedatetime
from datetime import datetime
# create a variable
todays_date = datetime.now()
print(todays_date)上面的代码将打印当前时间,包括年、月、日、小时、分钟和秒。
使用字符串
Python 模块有两个内置方法,和 ,分别帮助 Python 程序员将字符串转换或解析为对象,将 Python 字符串转换或解析为对象。让我们回顾一下这些。datetimestrptime()strftime()timetimeDateTime
strptime()
该方法将字符串和数据转换为对象。下面的代码说明了如何在 Python 中使用这些方法:strptime()datetimeDateTime
from datetime import datetime
date_in_string = ‘2021-11-19’
convert_date_to_object = datetime.strptime(date_in_string, ‘%Y-%m-%d’)
print(convert_date_to_object)在上面的代码中,该函数接受两个参数,变量和第二个字符串,该字符串显示格式或占位符,演示应如何表示第一个变量。strptimedate_in_string
以下列表显示了表示 Python 变量的各种格式:DateTime
%a: abbreviated weekday as Sun, Mon
%A: weekdays full name
%w: weekdays as number
%d: days in number and zero-padded 01, 02
%b: Months abbreviate as Apr, Jun
%B: Months full name April, June
%m: months in number and zero-padded 03, 06
%y: Year without century 21, 20, 19
%Y: Year with century 2021, 2020, 2019
%H: 24 hours clock 00 - 23 zero-padded
%I: 12 hours clock 01 - 12 zero-padded
%p: Period of the day as AM/PM
%M: Minutes from 00 - 59 zero-padded
%s: seconds from 00 - 59 zero-padded
%f: microseconds 6 decimal places若要确认输出是对象,请通过运行以下代码来使用该函数:type
print(type(convert_date-to_object))strftime()
该方法将对象转换为字符串。下面的代码说明了如何在 Python 中使用该方法:strftime()DateTimestrftime()
from datetime import datetime
time_as_object = datetime.today()
print(time_as_object)
# to check the type use the code below
print(type(time_as_object))
# convert time_as_object to string
time_as_string = time_as_object.strftime(“%Y-%m-%d %H:%M:%S”)
print(time_as_string)
# to add the milliseconds use .%f
time_as_string = time_as_object.strftime(“%Y-%m-%d %H:%M:%S.%f”)
print(time_as_string)
# check type
print(type(time_as_string))注意:还有更多可用的格式,我没有在这里包括。您可以参考上面的列表并尝试不同的练习形式。
date对象:提取星期几和月中的某天
Python 对象将日期表示为年、月和日。在本节中,我们将从类中提取星期几、月中的某天和年份。我们还将使用日历模块获取日期的名称。datedate
Python 编程语言从星期一开始计算星期几。作为一般编程规则,第一天从 index 开始。0
在我们提取类的内容之前,让我们使用以下代码片段说明 Python 如何读取一周中的几天:date
import calendar
for i in calendar.day_name:
print(i)
# i represent items in calendar.day_name上述程序的结果如下:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday有了这个细节,我们可以开始从中提取天数和月份。下面的代码片段说明了如何提取各种组件:date
from datetime import datetime
import calendar
day_variable = datetime.now
print(day_variable)
# this will print year, month, date and the time the code was run
# to print index of day of the week
print(day_variable.weekday)
# to print the date
print(day_variable.day)
# to print the month in number
print(day_variable.month)
# to print the year
print(day_variable.year)
# to print the name of the day
print(calendar.day_name[day_variable.weekday()])time对象:提取小时、分钟和秒
该对象是 Python 模块中的一个类,表示一天中的本地时间。让我们看看如何从时间类中提取 、 和组件。Python 时间构造函数采用一些可选参数,最常用的参数是小时、分钟、秒和毫秒。timedatetimehourminutessecond
下面的代码片段说明了如何使用 Python 对象:time
from datetime import time
# instantiate a new time object
time_variable = time()
# extract its component
print('The hour is: ', time_variable.hour)
print('The miniute: ', time_variable.minute)
print('The second is: ', time_variable.second)上述代码的结果如下:
0
0
0. 上面的代码表示 Python 类中的默认值 、 和。让我们继续实例化一个接受三个参数的构造函数:hourminutesecondtime
from datetime import time
# instantiate a new time object
time = time(7, 57, 5)
# extract its component
print(“The hour is: ”, time.hour)
print(“The minute is: ”, time.minute)
print(“The second is: ”, time.second)上述代码的结果将是:
The hour is: 7
The minute is: 57
The second is: 5在上面的示例中,我们对值进行了硬编码,但我们需要编写一个程序,从您的计算机获取本地时间。然后,我们将按照以下示例提取组件:time
from datetime import datetime
import calendar
time = datetime.now()
# print year, month, day, and time (hour, minute, seconds, and microseconds)
print(time.today())
# extract the component by printing them out
print(time.year)
# this will print the current year
# print the month
print(time.month)
# print the index of the day of the week
print(time.weekday())
# print the date of the month in a number format
print(time.day)
# print the name of the day of the month
print(calendar.day_name[time.weekday()])tzinfo:使用时区信息
您可能还记得,由于时区的变化或差异,Python 模块是必需的。 使用计算机上的时间,因为它没有任何关于时区的信息。datetimedatetime.now()
假设开发人员正在处理一个具有全球受众的项目,他们需要根据用户的时区显示时间。Python 提供了一个非常有用的模块来处理这样的情况,即模块。pytz
该模块可帮助开发人员处理时区转换。下面的代码片段说明了如何使用 Python 模块:pytzpytz
from datetime import datetime
import pytz
# get the local time
local_time = datetime.now()
print(“Local time is: “, local_time)
tz_Lagos = pytz.timezone(‘Africa/Lagos’)
datetime_in_Lagos = datetime.now(tz_Lagos)
print(datetime_in_Lagos)
# use f string and print timezone and time together
print(f‘ Time in {tz_Lagos} is {datetime_in_Lagos}’)根据您在地球上的位置,您可以使用此 Python 模块并打印任何时区的时间。例如,我在非洲拉各斯,我想打印欧洲莫斯科的当前时间。我可以使用下面的代码片段来做到这一点:
from datetime import datetime
import pytz
timeZone_in_Moscow = pytz.timezone(‘Europe/Moscow’)
datetime_in_Moscow = datetime.now(timeZone_in_Moscow)
print(datetime_in_Moscow)该程序会将莫斯科的当前时间打印到控制台,即使我在非洲。现在我们知道了如何获取不同时区的时间,让我们谈谈.timedelta
蟒蛇对象timedelta
Python 是一个表示持续时间的对象,持续时间是两个时间或日期之间的差值。在 Python 模块中找到,采用所有初始值设置为零的可选参数。timedeltadatetimetimedelta
要获取两个时间或日期之间的差异,我们首先需要导入:timedelta
# import timedelta
from datetime import timedelta, datetime
# get current time
today = datetime.now()
# create a timedelta
weeks_ago = timedelta(weeks=4)
# print the difference between today and 4 weeks ago
difference = today - week_ago
print(difference)对象可以采用以下参数:周、秒、分钟、毫秒、微秒、小时和天。上述代码的结果将根据您运行程序的时间而有所不同。timedelta
了解类tzinfo
tzinfo是 Python 模块中的另一个类,在处理有关特定时区的详细信息时很有用。Python 类是一个抽象类,因此无法实例化。datetimetzinfo
要实现此类中的各种方法,必须从中派生一个具体的子类。现在可以将 的实例传递到 and 构造函数对象中。下面列出了类中存在的一些方法:tzinfodatetimetimetzinfo
- utcoffset(dt):作为对象返回本地时间与 UTC 的偏移量timedelta
- dst(dt):如果夏令时不可用,则返回。否则,它将夏令时作为对象返回Nonetimedelta
- tzname(dt):以字符串形式返回相应的对象时区名称datetime
蟒蛇模块示例应用程序datetime
让我们使用到目前为止介绍的信息来构建一个生日计算器,该计算器将打印用户的当前年龄和他们下一个生日的倒计时。倒计时将包括他们下一个生日前剩余的天数、小时数、分钟数和秒数,以及他们生日的星期几。我们的生日计算器将用户的生日作为输入:Line 20
import calendar
import datetime
# the neccessary modules we need
current_time_and_date = datetime.datetime.now()
# access the current date and time
# access today name
today_name = calendar.day_name[current_time_and_date.weekday()]
# declare a time object
class Time(object):
current_time_and_date = datetime.now()
def __init__(self, year=1, month=1, day=1, hour=0, minute=0, second=0):
self.date = datetime.datetime(year, month, day, hour, minute, second
# initialize two variables to hold today's date and the birthday respectively
today = Time().current_time_and_date
birthday = Time(1960, 12, 4).date
# declare a function that returns today using f-string
def name_of_day_of_the_week():
return f'Today is {today_name}'
# declare a function that receives birthday as an argument
def birthday_records(birthday_param):
age = today.year - birthday_param.year
if (birthday_param.month == today.month) and (birthday_param.day <= today.day):
pass
elif birthday_param.month < today.month:
pass
else
age = age - 1
birthday_now = Time(today.year, birthday_param.month, birthday_param.day).date
next_birthday = str(birthday_now - today).split()
if len(next_birthday) > 1:
days = int(next_birthday[0])
time = next_birthday[2].split(":")
else:
days = 365
time = next_birthday[0].split(":")
hours = [0]
minutes = [1]
seconds = \[2\][:2]
if days < 0 and days != 365:
days += 365
elif days == 365:
days = 0
else:
days = days
print("2 You are %s years old; and is next birthday is %sd:%sh:%sm:%ss" & (age, days, hours, minutes, seconds))
#invoke the necessary functions
print(name_of_day_of_the_week())
birthday_records(birthday)结论
在本教程中,我们学习了如何使用 Python 模块处理日期和时间。
我们还介绍了如何使用 Python 模块提供的各种类。最后,我们通过构建一个示例应用程序来使用我们的知识,该应用程序倒计时到用户下一个生日的天数、分钟数和秒数。datetimedatetime
在 Python 中处理日期和时间并不总是那么简单。在本文中,我们学习了如何使用 Python 模块简化流程。希望本文提供了一些说明来帮助您入门。如果您有任何疑问,请务必发表评论。datetime
相关推荐
- 笔记本内存怎么扩大(笔记本电脑内存怎么扩大)
-
笔记本系统内存怎么的扩大,答笔记本内存可用下列方法扩大:1、打开【我的电脑】。2、在【计算机】位置点右键,选择【属性】。3、进入系统界面,点击【高级系统设置】。4、点击【高级】-【设置】。5、在【性能...
- visio2010安装包(visio 2010安装)
-
在该对话框中的“选择页”列表中,显示了目前绘图文档中所有的绘图页,包括前景页和背景页等。单击选择所需要的任意页,然后即可单击“确定”...Visio2010和2016都有各自的优势。Visio201...
- windows11开机密码忘了(windows11开机密码忘了怎么办)
-
1.使用安装光盘重装系统:如果你有安装Windows11的光盘,可以用它重装系统,这样就可以抹掉原来的密码,重新设置新的开机密码。2.使用系统安全模式:可以尝试使用Windows11的安全模式...
- 电脑怎么刷bios教程(电脑刷bios有什么好处)
-
刷主板bios的方法一 升级主板bios需要主板的最新biosS文件以及刷bios的工具,这些都可以在主板厂商的官方网站上获取到。首先,是下载你的最新版的bios,打开下载的winflash软件,备...
- win7gho和iso区别(windows7区别)
-
区别一:来源不一样1、ISO光盘镜像文件可以直接刻录成光盘使用(带启动),也可以说是一个压缩包!2、GHO是GHOST境像文件、是用GHOST备份的克隆文件,是用ghost恢复系统的时候使用的。区别二...
-
- 笔记本电脑突然蓝屏怎么解决
-
、可能是磁盘问题所导致的,将电脑关机后重新开机,在开机时不断按F8选择进入安全模式;2、按win+r打开运行窗口;3、输入cmd并确定;4、然后输入chkdsk/f/r并回车;5、最后按y退出页面,重启电脑系统会自动修复硬盘进行恢复即可。...
-
2025-12-23 07:51 off999
- 序列号官方查询(序列号查询工具)
-
华为提供了3个查询入口,华为官网、服务APP、华为终端客户服务公众号,您可选择其中一个入口查询设备权益信息。入口一、华为官网:登录华为消费者业务官网-服务支持-保修状态查询-填写序列号-查询-设备权益...
- windows8度(windows8度盘符怎么设置)
-
小度音箱配置网络失败怎么办?1、小度智能音箱连接的路由器名称一定要是英文,不能有中文和符号,这个大家要注意一下。ZNSJW.cow2、路由器网络的选择也有讲究,我们要选用2.4G的网络,5G的是连不上...
- 系统集成项目管理工程师成绩公布时间
-
中级系统集成考试成绩一般需要一个月左右的时间才能出来。1、因为中级系统集成考试是比较复杂且专业的考试,需要对考生的各种能力进行综合考察,需要时间进行精细评估和核查。2、同时,中级系统集成考试的参加人数...
- 苹果序列号查询方法(苹果序列号查询方式)
-
苹果查序列号入口可登陆苹果官网checkcoverage.apple.com进行查询,具体步骤如下:1、打开手机设置,点击“通用”2、进入页面后点击“关于本机”;3、页面跳转后,我们就可以看到本机的序...
-
- 字根表五笔口诀(字根表五笔口诀如何理解)
-
1区横起笔、G键:王旁青头兼五一;F键:土士二干十寸雨;D键:大三肆头古石厂;S键:木丁西边要无女;A键:工戈草头右框七。2区竖起笔、H键:目止具头卜虎皮;J键:日曰两竖与虫依;K键:口中两川三个竖;L键:田框四车甲单底;M键:山由贝骨下...
-
2025-12-23 04:51 off999
- 如何笔记本重装系统(笔记本重装系统的步骤)
-
重装系统就可以解决了,系统U盘制作及重装系统的操作步骤为:1.制作启动U盘:到实体店买个4-8G的U盘(可以要求老板帮忙制作成系统U盘即可省略以下步骤),上网搜索下载装机员U盘启动PE制作工具,将U盘...
- win7旗舰版显卡驱动(win7电脑显卡驱动)
-
步骤如下:1、首先我们打开桌面,右键单击此电脑再右键菜单选择属性。2、进入属性界面,点击设备管理器进入。3、进入设备管理器界面,点击显示适配器。4、展开显示适配器,可以看到一般电脑又集成显卡和独立显卡...
- 进入ie浏览器网页官网(贴吧热门评论)
-
ie浏览器的网页版登录入口是about:blank,即为“空白页”。空白页也被称为首页,是登录的入口,是用户打开浏览器时默认打开的网页,主要包含个人主页、网站网页、组织或活动主页、公司主页等。没有手...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
系统u盘安装(win11系统u盘安装)
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
