如何获取当前时间?


当前回答

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

如果你经常使用panda,你可以使用Timestamp,它相当于Python的Datetime:

In [1]: import pandas as pd

In [2]: pd.Timestamp.now()
Out[2]: Timestamp('2022-06-21 21:52:50.568788')

只是时间:

In [3]: pd.Timestamp.now().strftime("%H:%M:%S")
Out[3]: '21:53:01'

使用time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

您可以尝试以下操作

import datetime

now = datetime.datetime.now()
print(now)

or

import datetime

now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

示例输出:“2013-09-18 11:16:32”

请参阅strftime指令列表。