如何获取当前时间?
当前回答
在Python 3.9中,zoneinfo模块可以用于获取时区,而不是使用第三方库。
要获取特定时区中的当前时间,请执行以下操作:
from datetime import datetime
from zoneinfo import ZoneInfo
datetime.now(tz=ZoneInfo("Europe/Amsterdam"))
其他回答
前面的答案都是很好的建议,但我发现使用ctime()最简单:
In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'
这提供了当前本地时间的格式良好的字符串表示。
获取当前日期时间属性:
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("%T", time.localtime())
输出应如下所示
05:46:33
11:22:56
13:44:55
22:33:44
00:00:00
.iformat()在文档中,但这里还没有(这与@Ray Vega的回答非常相似):
>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录