如何获取当前时间?


当前回答

获取当前日期时间属性:

import datetime

currentDT = datetime.datetime.now()

print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)


#!/usr/bin/python
import time;

ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks

其他回答

默认情况下,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

使用日期时间:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150

对于没有日期的时钟时间:

>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150

要保存键入,可以从datetime模块导入datetime对象:

>>> from datetime import datetime

然后删除前缀datetime。从以上所有方面来看。

这个问题是针对Python的,但由于Django是Python中使用最广泛的框架之一,因此需要注意的是,如果您使用Django,您可以始终使用timezone.now()而不是datetime.datetime.now()。前者是时区“感知”,而后者不是。

有关timezone.now()背后的详细信息和原理,请参阅这个SO答案和Django文档。

from django.utils import timezone

now = timezone.now()

使用熊猫来获取当前的时间,有点过分了眼前的问题:

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

输出:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

因为还没有人提到它,这是我最近遇到的事情。。。pytz时区的fromutc()方法与datetime的utcnow()相结合是我发现的在任何时区中获取有用的当前时间(和日期)的最佳方法。

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

如果您只需要时间,那么可以使用local_time.time()获取时间。