如何获取当前时间?


当前回答

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

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

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

其他回答

要在11:34:23.751毫秒内精确获得3个小数点,请运行以下命令:

def get_time_str(decimal_points=3):
        return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

更多上下文:

我想用毫秒来计算时间。获取它们的简单方法:

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

但我只需要几毫秒,对吧?获取它们的最短方法:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

在最后一次乘法中添加或删除零以调整小数点的数量,或仅执行以下操作:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

Do

from time import time

t = time()

t-浮点数,适用于时间间隔测量。

Unix和Windows平台有一些不同。

对UTC日期时间、本地日期时间使用此方法,并转换上午和下午

import pytz
from datetime import datetime

#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)

#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)

可以使用ctime()执行此操作:

from time import time, ctime
t = time()
ctime(t)

输出:

2019年9月14日星期六21:27:08

这些输出不同,因为ctime()返回的时间戳取决于您的地理位置。

如果您将其用于django datetime有时在服务器上无法工作,所以我建议使用时区

但要使用django时区,您应该在设置中设置您的国家/地区时区代码。py

TIME_ZONE = 'Asia/Tashkent'

那你就可以用它了

from django.utils import timezone

timezone.now() // for date time

timezone.now().year // for yaer

timezone.now().month // for month

timezone.now().day // for day 

timezone.now().date // for date

timezone.now().hour // for hour

timezone.now().weekday // for minute

或者如果您想在python上使用

import time

time.strftime('%X') // '13:12:47'

time.strftime('%x') // '01/20/22'

time.strftime('%d') // '20' day

time.strftime('%m') // '01' month

time.strftime('%y') // '20' year

time.strftime('%H') // '01' hour

time.strftime('%M') // '01' minute

time.strftime('%m') // '01' second