亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python DateTime、TimeDelta、Strftime(Format) 与示例

在 Python 中,日期、时间和日期时间 类提供了许多处理日期、时间和时间间隔的函数。 Python 中的日期和日期时间是对象,因此当您操作它们时,您实际上是在操作对象,而不是字符串或时间戳。每当您操作日期或时间时,都需要导入 datetime 函数。

Python中的日期时间类主要分为5个类。

在本教程中,我们将学习-

如何使用日期和日期时间类

第 1 步 ) 在 Python 中运行日期时间格式的代码之前,请务必导入 Python 日期时间模块,如下面的屏幕截图所示。

这些导入语句是 Python 库中预定义的功能片段,可让您操作日期和时间,而无需编写任何代码。

在执行 Python 日期时间格式代码之前请考虑以下几点

from datetime import date

这一行告诉 Python 解释器从 Python 中的 datetime 模块导入日期类。我们没有为此日期功能编写代码,只是将其导入以供我们使用

第 2 步 ) 接下来,我们创建一个日期对象的实例。

第 3 步 ) 接下来,我们打印日期并运行代码。

输出符合预期。

使用 date.today() 打印日期

date.today 函数有几个与之相关的属性。我们可以打印个别的日/月/年和许多其他的东西

我们来看一个例子

今天的工作日编号

date.today() 函数还为您提供工作日编号。这是工作日表,星期一为 0,星期日为 6

Day
工作日编号
星期一
0
星期二
1
星期三
2
星期四
3
星期五
4
星期六
5
星期日
6


星期数对于索引取决于星期几的数组很有用。

Python 当前日期和时间:now() today()

步骤 1) 像日期对象一样,我们也可以使用 “DATETIME OBJECTS” 在 Python 中。 Python 日期和时间对象以小时、分钟、秒和毫秒为单位提供日期和时间。

当我们执行 datetime 的代码时,它会给出当前日期和时间的输出。

步骤 2) 配合“DATETIME OBJECT”,也可以调用时间类。

假设我们只想打印当前时间而不打印日期。

t = datetime.time(datetime.now())

这会给我时间。所以让我们运行这个程序。

好的,你可以看到我在这里得到了日期和时间。然后下一行,我自己有时间

步骤 3) 我们会将工作日索引器应用到工作日的 arrayList 以了解今天是哪一天


这是使用 datetime now 获取当前日期和时间的完整代码

from datetime import date
from datetime import time
from datetime import datetime
def main():
    ##DATETIME OBJECTS
    #Get today's date from datetime class
    today=datetime.now()
    #print (today)
    # Get the current time
    #t = datetime.time(datetime.now())
    #print "The current time is", t
    #weekday returns 0 (monday) through 6 (sunday)
    wd=date.weekday(today)
    #Days start at 0 for monday
    days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
    print("Today is day number %d" % wd)
    print("which is a " + days[wd])

if __name__== "__main__":
    main()

如何使用 Strftime() 格式化日期和时间输出

到目前为止,我们已经了解了如何在 Python 中使用 datetime 和 date 对象。我们将更进一步,学习如何使用格式化函数来格式化时间和日期。

步骤 1) 首先,我们将看到如何格式化年份的简单步骤。举个例子更好理解。

步骤 2) 现在,如果您将 ("%Y") 替换为小写,即 ("%y) 并执行代码,输出将仅显示 (18) 而不是 (2018)。如下图所示,年份的世纪不会显示

步骤 3) strf函数可以分别声明日、日、月、年。还可以通过 strftime 函数中控制代码的小改动来格式化文本的样式。

在 strftime 函数中,如果将 (%a) 替换为大写 A,即 (%A),输出将打印为“Firday”,而不仅仅是缩写“Fri”。

第 4 步) 借助“Strftime”函数,我们还可以检索本地系统时间、日期或两者。

  1. %C- 表示本地日期和时间
  2. %x- 表示本地日期
  3. %X- 表示当地时间

在输出中,你可以看到预期的结果

第 5 步) “strftime 函数”允许您以 24 小时或 12 小时的任何格式调用时间。

只需定义控制代码,如 %I/H 代表小时、%M 代表分钟、%S 代表秒,就可以调用不同格式的时间

12 小时 时间被声明 [print now.strftime(“%I:%M:%S %p) ]

24 小时 声明时间 [print now.strftime(“%H:%M”)]

这是将日期时间转换为字符串对象的完整代码。

#
#Example file for formatting time and date output
#
from datetime import datetime
def main():
   #Times and dates can be formatted using a set of predefined string
   #Control codes
      now= datetime.now() #get the current date and time
      #%c - local date and time, %x-local's date, %X- local's time
      print(now.strftime("%c"))
      print(now.strftime("%x"))
      print(now.strftime("%X"))
##### Time Formatting ####
      #%I/%H - 12/24 Hour, %M - minute, %S - second, %p - local's AM/PM
      print(now.strftime("%I:%M:%S %p")) # 12-Hour:Minute:Second:AM
      print(now.strftime("%H:%M")) # 24-Hour:Minute

if __name__== "__main__":
    main()

什么是 Python 中的 Timedelta?

Python 中的时间增量 是一个表示持续时间的对象。它主要用于计算两个日期和时间之间的持续时间。它还用于检索具有一些增量日期和时间的对象。 timedelta 对象支持加法、减法、乘法、除法等数学运算。

如何使用 Timedelta 对象

使用 Python timedelta 对象,您可以估计未来和过去的时间。 换句话说,它是预测任何特殊日子、日期或时间的时间跨度。

请记住,此功能不是用于打印时间或日期,而是用于计算未来或过去的东西 .让我们看一个 Python timedelta 示例来更好地理解它。

步骤 1) 运行Timedelta Objects需要先声明import语句,然后执行代码

  1. 为 timedelta 编写导入语句
  2. 现在编写代码以从时间增量中打印出对象,如屏幕截图所示
  3. 运行代码。 timedelta 代表 365 天 8 小时 15 分钟的跨度,并且打印出来的时间相同

令人困惑?下一步会有帮助-

步骤 2) 让我们获取今天的日期和时间来检查我们的导入语句是否运行良好。当代码执行时,它会打印出今天的日期,这意味着我们的 import 语句运行良好

步骤 3) 我们将看到如何通过 delta 对象检索一年后的日期。当我们运行代码时,它会给出预期的输出。

第 4 步) 另一个如何使用时间增量从当前日期和时间计算未来日期的示例

第 5 步) 让我们看一个更复杂的例子。我想确定新年过后多少天。以下是我们将如何进行

输出显示“元旦已经过去了 11 天。”

这是完整的工作代码

#
# Example file for working with timedelta objects
#
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print (timedelta(days=365, hours=8, minutes=15))
# print today's date
print ("today is: " + str(datetime.now()))
# print today's date one year from now
print ("one year from now it will be:" + str(datetime.now() + timedelta(days=365)))
# create a timedelta that uses more than one argument
# print (in one week and 4 days it will be " + str(datetime.now() + timedelta(weeks=1, days=4)))
# How many days until New Year's Day?
today = date.today()  # get todays date
nyd = date(today.year, 1, 1)  # get New Year Day for the same year
# use date comparison to see if New Year Day has already gone for this year
# if it has, use the replace() function to get the date for next year
if nyd < today:
    print ("New Year day is already went by %d days ago" % ((today - nyd).days))

Python 2 示例

from datetime import date
from datetime import time
from datetime import datetime
def main():
 	##DATETIME OBJECTS
    #Get today's date from datetime class
	today=datetime.now()
	#print today
	# Get the current time
	#t = datetime.time(datetime.now())
	#print "The current time is", t
	#weekday returns 0 (monday) through 6 (sunday)
        wd = date.weekday(today)
	#Days start at 0 for monday
        days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
        print "Today is day number %d" % wd
        print "which is a " + days[wd]

if __name__== "__main__":
    main()
#
#Example file for formatting time and date output
#
from datetime import datetime
def main():
   #Times and dates can be formatted using a set of predefined string
   #Control codes
      now= datetime.now() #get the current date and time
      #%c - local date and time, %x-local's date, %X- local's time
      print now.strftime("%c")
      print now.strftime("%x")
      print now.strftime("%X")
##### Time Formatting ####   
      #%I/%H - 12/24 Hour, %M - minute, %S - second, %p - local's AM/PM
      print now.strftime("%I:%M:%S %p") # 12-Hour:Minute:Second:AM
      print now.strftime("%H:%M") # 24-Hour:Minute   

if __name__== "__main__":
    main()
#
# Example file for working with timedelta objects
#
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

# construct a basic timedelta and print it
print timedelta(days=365, hours=8, minutes=15)
# print today's date
print "today is: " + str(datetime.now())
# print today's date one year from now
print "one year from now it will be:" + str(datetime.now() + timedelta(days=365))
# create a timedelta that uses more than one argument
# print "in one week and 4 days it will be " + str(datetime.now() + timedelta(weeks=1, days=4))
# How many days until New Year's Day?
today = date.today()  # get todays date
nyd = date(today.year, 1, 1)  # get New Year Day for the same year
# use date comparison to see if New Year Day has already gone for this year
# if it has, use the replace() function to get the date for next year
if nyd < today:
    print "New Year day is already went by %d days ago" % ((today - nyd).days)

总结

为了以简单和复杂的方式操作日期和时间,datetime 模块提供了不同的类或类别,例如

使用日期时间对象

用“str f time function”格式化超时

时间增量对象


Python

  1. Python 日期时间
  2. 如何在 Python 中获取当前日期和时间?
  3. Python获取当前时间
  4. Python时间模块
  5. Python 睡眠()
  6. Python Print() 语句:如何通过示例打印
  7. 带有示例的 Python 字符串计数()
  8. Python String format() 举例说明
  9. Python String find() 方法及示例
  10. 带有示例的 Python Lambda 函数
  11. 带有示例的 Python round() 函数
  12. 带有示例的 Python map() 函数