如何获取当前时间?
当前回答
因为还没有人提到它,这是我最近遇到的事情。。。pytz时区的fromutc()方法与datetime的utcnow()相结合是我发现的在任何时区中获取有用的当前时间(和日期)的最佳方法。
from datetime import datetime
import pytz
JST = pytz.timezone("Asia/Tokyo")
local_time = JST.fromutc(datetime.utcnow())
如果您只需要时间,那么可以使用local_time.time()获取时间。
其他回答
使用熊猫来获取当前的时间,有点过分了眼前的问题:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
输出:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
获取当前日期时间属性:
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
试试这个:-
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
执行dir(date)或包括包在内的任何变量。您可以获取与变量关联的所有属性和方法。
这个问题不需要一个新的答案。。。然而,一个闪亮的新玩具/模块就足够了。这就是摆库,它似乎做了箭头所尝试的那种事情,除了没有困扰箭头的固有缺陷和缺陷。
例如,原始问题的答案:
>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00
有很多标准需要解决,包括多个RFC和ISO。曾经把它们混在一起;不用担心,稍微了解一下dir(钟摆常量),但这里有一点不仅仅是RFC和ISO格式。
当我们说本地时,我们是什么意思?我的意思是:
>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>
想必你们中的大多数人都是指其他地方。
然后继续。长话短说:Pendulum试图在日期和时间上做HTTP请求所做的事情。它值得考虑,特别是它的易用性和广泛的文档。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录