如何获取当前时间?


当前回答

from time import ctime

// Day {Mon,Tue,..}
print ctime().split()[0]
// Month {Jan, Feb,..}
print ctime().split()[1]
// Date {1,2,..}
print ctime().split()[2]
// HH:MM:SS
print ctime().split()[3]
// Year {2018,..}
print ctime().split()[4]

当您调用ctime()时,它会将秒转换为格式为“Day Month Date HH:MM:SS Year”(例如:“Wed January 17 16:53:22 2018”)的字符串,然后调用split()方法,该方法将从字符串['Wed','Jan','17','16:56:45','2018'中列出一个列表(默认delimeter为空格)。

括号用于在列表中“选择”所需参数。

应该只调用一个代码行。人们不应该像我那样称呼它们,这只是一个例子,因为在某些情况下,你会得到不同的值,这是罕见但并非不可能的情况。

其他回答

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

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

如果您需要时区感知解决方案。我喜欢使用以下5行代码来获取当前时间。

from datetime import datetime
import pytz

# Specify the timezone
my_time_zone = pytz.timezone('Asia/Singapore')

# Pass the timezone to datetime.now() function
my_time = datetime.now(my_time_zone)

# Convert the type `my_time` to string with '%Y-%m-%d %H:%M:%S' format.
current_time = my_time.strftime('%Y-%m-%d %H:%M:%S') # current_time would be something like 2023-01-23 14:09:48

您可以使用pytz.all_timezones查找所有时区的列表。

%Y-%m-%d%H:%m:%S中符号的含义可以在geeksfgeeks Python strftime()函数中找到

使用日期时间:

>>> 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 time
>>> print(time.strftime("%d/%m/%Y"))
06/02/2015

使用大写Y表示全年,使用Y表示2015年2月6日。

您也可以使用以下代码来延长时间:

>>> time.strftime("%a, %d %b %Y %H:%M:%S")
'Fri, 06 Feb 2015 17:45:09'