Python 调用 datetime 当前时间?

Python call datetime current hour?

一石二鸟,我有两个问题

  1. 如何准确调用当前日期?当前时间?
  2. 我怎样才能准确调用特定时间?不特定于某一天。
from datetime import date, datetime

current_time = datetime.utcnow() # Call current time
start_time = datetime.time.hour(17)
end_time = datetime.time.hour(20)

使用 Python

中的 datetime 模块

示例 Python 3

获取当前时间

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S") # H - hour, M- minute, S - second
print("Current Time =", current_time)

获取当前时间

from datetime import datetime

now = datetime.now()

current_hour = now.strftime("%H") 
print("Current hour =", current_hour)

获取当前日期

from datetime import date

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

同样,使用 %S 表示秒,%M 表示分钟,%H 表示小时。 %d 表示日,%m 表示月,%Y 表示年。

额外内容

一起打印日期和时间

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)

根据time-zone

打印
from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S

来源:

Date

Time

另请查看:

您非常接近答案。开始了。

import datetime

导入日期时间模块后,您只需调用:

current_time = datetime.datetime.now()

如果您想访问数据,您有 yearmonthdayhourminutesecond , microsecond 方法:

current_time.day # Will return 17

要指定一个给定的时间,你只需要一个变量,你有 datetime.time class.

An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.

start_time = datetime.time(17, 25, 30) # (17:25:30)

和以前一样。可以通过调用其方法来访问数据。

start_time.hour # will return 17

这里有文档: :) datetime module