如何获取当前时间?


当前回答

now()的属性可用于获取python中的当前时间:

# importing datetime module for now()
import datetime
    
# using now() to get current time
current_time = datetime.datetime.now()
    
# Printing attributes of now().
print ("The attributes of now() are : ")
    
print ("Year : ", end = "")
print (current_time.year)
    
print ("Month : ", end = "")
print (current_time.month)
    
print ("Day : ", end = "")
print (current_time.day)
    
print ("Hour : ", end = "")
print (current_time.hour)
    
print ("Minute : ", end = "")
print (current_time.minute)
    
print ("Second : ", end = "")
print (current_time.second)
    
print ("Microsecond : ", end = "")
print (current_time.microsecond)

其他回答

如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“timeit”模块:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

如果您需要时区感知解决方案。我喜欢使用以下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 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'

这就是我最终要做的:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

此外,该表是选择适当格式代码以按照您想要的方式格式化日期的必要参考(来自Python“datetime”文档)。

如果您将其用于django datetime有时在服务器上无法工作,所以我建议使用时区

但要使用django时区,您应该在设置中设置您的国家/地区时区代码。py

TIME_ZONE = 'Asia/Tashkent'

那你就可以用它了

from django.utils import timezone

timezone.now() // for date time

timezone.now().year // for yaer

timezone.now().month // for month

timezone.now().day // for day 

timezone.now().date // for date

timezone.now().hour // for hour

timezone.now().weekday // for minute

或者如果您想在python上使用

import time

time.strftime('%X') // '13:12:47'

time.strftime('%x') // '01/20/22'

time.strftime('%d') // '20' day

time.strftime('%m') // '01' month

time.strftime('%y') // '20' year

time.strftime('%H') // '01' hour

time.strftime('%M') // '01' minute

time.strftime('%m') // '01' second