如何获取当前时间?
当前回答
import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time
date将打印日期,time将打印时间。
其他回答
试试这个:-
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“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))
获取当前日期时间属性:
import datetime
currentDT = datetime.datetime.now()
print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)
#!/usr/bin/python
import time;
ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks
最快的方法是:
>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
如果您需要时区感知解决方案。我喜欢使用以下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()函数中找到
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 单元测试:日期时间。现在
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?