如何获取当前时间?


当前回答

import datetime
import pytz # for timezone()
import time

current_time1 = datetime.datetime.now()
current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
current_time3 = datetime.datetime.utcnow()
current_time4 = datetime.datetime.now().isoformat()
current_time5 = time.gmtime(time.time())

print("datetime.datetime.now():", current_time1)
print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2)
print("datetime.utcnow():", current_time3)
print("datetime.datetime.now().isoformat():", current_time4)
print('time.gmtime(time.time()): ', current_time5)

其他回答

以下是我用来获取时间而不必格式化的内容。有些人不喜欢拆分方法,但它在这里很有用:

from time import ctime
print ctime().split()[3]

它将以HH:MM:SS格式打印。

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

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

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

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

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

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

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