如何获取当前时间?


当前回答

为什么不问问美国海军的官方计时员美国海军天文台?

import requests
from lxml import html

page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

如果你住在华盛顿地区(像我一样),延迟可能不会太差。。。

其他回答

试试这个:-

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

这很简单。尝试:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]

默认情况下,now()函数以YYYY-MM-DD HH:MM:SS:MS格式返回输出。使用以下示例脚本获取Python脚本中的当前日期和时间,并在屏幕上打印结果。使用以下内容创建文件getDateTime1.py。

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

输出如下所示:

2018-03-01 17:03:46.759624

now()的属性可用于获取python中的当前时间:

# importing datetime module for now()
import datetime
    
# using now() to get current time
current_time = datetime.datetime.now()
    
# Printing attributes of now().
print ("The attributes of now() are : ")
    
print ("Year : ", end = "")
print (current_time.year)
    
print ("Month : ", end = "")
print (current_time.month)
    
print ("Day : ", end = "")
print (current_time.day)
    
print ("Hour : ", end = "")
print (current_time.hour)
    
print ("Minute : ", end = "")
print (current_time.minute)
    
print ("Second : ", end = "")
print (current_time.second)
    
print ("Microsecond : ", end = "")
print (current_time.microsecond)

.iformat()在文档中,但这里还没有(这与@Ray Vega的回答非常相似):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'