如何获取当前时间?


当前回答

如果您需要时区感知解决方案。我喜欢使用以下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()函数中找到

其他回答

如果您已经在使用numpy,那么可以直接使用numpy.datetime64()作用

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用pandas,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))
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为空格)。

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

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

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

Do

from time import time

t = time()

t-浮点数,适用于时间间隔测量。

Unix和Windows平台有一些不同。