如何获取当前时间?


当前回答

使用日期时间:

>>> 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。从以上所有方面来看。

其他回答

import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time

date将打印日期,time将打印时间。

这个问题不需要一个新的答案。。。然而,一个闪亮的新玩具/模块就足够了。这就是摆库,它似乎做了箭头所尝试的那种事情,除了没有困扰箭头的固有缺陷和缺陷。

例如,原始问题的答案:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

有很多标准需要解决,包括多个RFC和ISO。曾经把它们混在一起;不用担心,稍微了解一下dir(钟摆常量),但这里有一点不仅仅是RFC和ISO格式。

当我们说本地时,我们是什么意思?我的意思是:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

想必你们中的大多数人都是指其他地方。

然后继续。长话短说:Pendulum试图在日期和时间上做HTTP请求所做的事情。它值得考虑,特别是它的易用性和广泛的文档。

如果需要当前时间作为时间对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
import datetime

todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12

# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38

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

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