百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python 模块:处理日期和时间datetime

off999 2024-09-29 15:59 56 浏览 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

  1. utcoffset(dt):作为对象返回本地时间与 UTC 的偏移量timedelta
  2. dst(dt):如果夏令时不可用,则返回。否则,它将夏令时作为对象返回Nonetimedelta
  3. 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

相关推荐

比特彗星app安卓版下载(比特彗星app安卓版下载苹果)

如果你在使用比特彗星下载时遇到下载速度慢的问题,可以尝试以下几种解决方法:1.检查网络连接:首先,确保你的网络连接稳定并且速度正常。你可以尝试打开其他网页或进行其他网络活动,以确定是否存在网络问题。...

课件模板ppt免费(课件模板ppt免费软件)
  • 课件模板ppt免费(课件模板ppt免费软件)
  • 课件模板ppt免费(课件模板ppt免费软件)
  • 课件模板ppt免费(课件模板ppt免费软件)
  • 课件模板ppt免费(课件模板ppt免费软件)
捕鱼达人千炮版下载官网(捕鱼达人经典原版下载)

要在捕鱼达人千炮版中进行交易,首先需要进入游戏的交易中心。在交易中心中,你可以浏览其他玩家发布的交易信息,或者自己发布交易需求。如果你找到了感兴趣的交易,可以与对方进行私聊,商讨交易细节和价格。一旦双...

游戏盒大全 安装(游戏盒大全 安装最新版)

要安装统一游戏盒子,首先需要在您的设备上下载并安装统一游戏盒子的应用程序。您可以在应用商店中搜索统一游戏盒子,然后点击安装按钮进行下载。安装完成后,打开应用程序并按照提示进行设置和登录。一旦登录成功,...

闹钟下载(闹钟下载正版)

苹果下载闹钟铃声方法如下:1.在手机上下载好爱思助手app,然后打开“爱思助手”软件,点击打开该app。2.点击进去后,点击页面底部的“发现”按钮,在“发现”页面中,找到“铃声”。3.之后在“铃声”的...

高清免费观看电视软件(永久免费观看的电视剧软件)

1.有免费在线看高清电视的网站。2.因为有些网站提供免费的高清电视节目,可以通过网络直接观看,不需要付费。3.除了免费在线观看高清电视的网站,还有一些付费的订阅平台,可以提供更多的高清电视节目选...

交管12123成绩查询(交管12123成绩查询怎么查)
  • 交管12123成绩查询(交管12123成绩查询怎么查)
  • 交管12123成绩查询(交管12123成绩查询怎么查)
  • 交管12123成绩查询(交管12123成绩查询怎么查)
  • 交管12123成绩查询(交管12123成绩查询怎么查)
flash下载安卓版下载(flashget安卓下载)

通过iTunes上的iTunesstore或者iPhone上的AppStore下载要是越狱版本91助手也可以下载而且有更多免费的游戏就是说你的电脑没有flash插件,需要安装flash插件才能...

模拟农场20(模拟农场20国产收割机)
  • 模拟农场20(模拟农场20国产收割机)
  • 模拟农场20(模拟农场20国产收割机)
  • 模拟农场20(模拟农场20国产收割机)
  • 模拟农场20(模拟农场20国产收割机)
电子公章印章在线制作(电子公章印章在线制作教程)

首先说明:电子公章制作需要有授权才能够进行!公章做成电子版可以通过Word来进行。具体方法步骤如下:1、准备工作:首先需要你(妳)将实体印章拍成图片格式上传到计算机保存桌面。2、制作操作:打开计算机办...

12306掐点抢票技巧(抢不到票去人工窗口能买到吗)

1、提前做好准备:在12306官网上预订车票前,先登录账号并保存好乘车人信息和常用联系人信息。此外,在购票日前,可以提前进行车次和座位的查询和选择。2、时间选择:00:00到08:00。3、车次选择:...

qq炫舞官网掌上炫舞(qq炫舞官方网站最新活动)

你好,进入掌上炫舞商城的方法如下:1.打开掌上炫舞游戏,进入游戏主界面。2.点击屏幕左下角的“商城”按钮。3.进入商城后,可以选择购买游戏中的道具、礼包等物品。4.在商城中选择要购买的物品后,...

西瓜音乐免费听(西瓜音乐免费听歌的app)
西瓜音乐免费听(西瓜音乐免费听歌的app)

TOP15:少年原唱:梦然热度值:1,013,022我还是从前那个少年没有一丝丝改变抖音梦然-《少年》mvTOP14:好想爱这个世界啊原唱:华晨宇热度值:1,013,096不想离开当你的笑容绽开这世界突然填满色彩华晨宇新歌《好想...

2026-02-03 17:43 off999

酷酷狗app正版下载安装(酷狗音乐下载最新版酷)

卖八个金,目前六阶的酷酷狗以及松鼠都是属于不错的两个战宠,酷酷狗的平A伤害十分之高,与黑霸对比也不会落下风,当我们使用技能还可以增加大量伤害,大约等于黑霸的两倍。虽然说松鼠的伤害对比酷酷狗来说十分一...

迅雷app(迅雷app下载安装官网手机版)
迅雷app(迅雷app下载安装官网手机版)

首先打开迅雷app,点击我的转存然后点击我们下载的文件然后点击左下角下载就好拉迅雷下载完的视频是直接保存到我的转存里。如果要想再把我的转存里面文件,下载到手机上,首先选择底部云盘图标进入我的转存页面,找到里面要下载的视频,勾选打√,下面会出...

2026-02-03 17:03 off999

取消回复欢迎 发表评论: