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

如何在 Python 中获取当前日期和时间?

如何在 Python 中获取当前日期和时间?

在本文中,您将学习在 Python 中获取今天的日期和当前日期和时间。我们还将使用 strftime() 方法将日期和时间格式化为不同的格式。

视频:Python 中的日期和时间

您可以通过多种方式获取当前日期。我们将使用 date datetime 模块的类来完成这个任务。


示例 1:Python 获取今天的日期

from datetime import date

today = date.today()
print("Today's date:", today)

在这里,我们导入了 date datetime 中的类 模块。然后,我们使用 date.today() 获取当前本地日期的方法。

顺便说一句,date.today() 返回一个 date 对象,分配给 today 上述程序中的变量。现在,您可以使用 strftime() 方法创建一个以不同格式表示日期的字符串。


示例 2:不同格式的当前日期

from datetime import date

today = date.today()

# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)

# Textual month, day and year	
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)

# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)

# Month abbreviation, day and year	
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)

当你运行程序时,输出会是这样的:

d1 = 16/09/2019
d2 = September 16, 2019
d3 = 09/16/19
d4 = Sep-16-2019

如果需要获取当前日期时间,可以使用datetime datetime 的类 模块。

示例 3:获取当前日期和时间

from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
 
print("now =", now)

# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)	

您将像下面这样门控输出。

now = 2021-06-25 07:58:56.550604
date and time = 25/06/2021 07:58:56

在这里,我们使用了 datetime.now() 获取当前日期和时间。然后,我们使用 strftime() 以另一种格式创建一个表示日期和时间的字符串。


Python

  1. 电压和电流计算
  2. Python 关键字和标识符
  3. Python 语句、缩进和注释
  4. Python 日期时间
  5. Python获取当前时间
  6. Python时间模块
  7. Python 睡眠()
  8. 如何优化制造系统并节省时间
  9. Java - 日期和时间
  10. C++ 日期和时间
  11. Python - 日期和时间
  12. 第一次买车险怎么办?