【问题标题】:Python call datetime current hour?Python调用日期时间当前时间?
【发布时间】:2020-09-24 17:02:19
【问题描述】:

一石二鸟,我有两个问题

  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 python-3.x datetime python-datetime


【解决方案1】:

你已经很接近答案了。我们开始吧。

import datetime

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

current_time = datetime.datetime.now()

如果你想访问你有yearmonthdayhourminutesecondmicrosecond方法的数据:

current_time.day # Will return 17

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

一个理想化的时间,独立于任何特定的一天,假设每一天正好有 246060 秒。 (这里没有“闰秒”的概念。)属性:小时、分钟、秒、微秒和 tzinfo。

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

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

start_time.hour # will return 17

这里有文档::) datetime module

【讨论】:

    【解决方案2】:

    在 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)
    

    按时区打印

    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

    另请查看:Similar question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2011-12-10
      • 2013-03-10
      • 1970-01-01
      相关资源
      最近更新 更多