让 Python 打印一天中的一小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22021398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:05:21  来源:igfitidea点击:

Getting Python to Print the Hour of Day

pythonpython-3.xtime

提问by user3352353

I am using the following code to get the time:

我正在使用以下代码来获取时间:

import time

time = time.asctime()

print(time)

I end up with the following result:

我最终得到以下结果:

'Tue Feb 25 12:09:09 2014'

How can I get Python to print just the hour?

我怎样才能让 Python 只打印一个小时?

回答by pajton

import time
print (time.strftime("%H"))

回答by jonrsharpe

time.asctime()will create a string, so extracting the hours part is hard. Instead, get a proper time.struct_timeobject, which exposes the components directly:

time.asctime()将创建一个字符串,因此很难提取小时部分。相反,获取一个适当的time.struct_time对象,它直接公开组件:

t = time.localtime() # gives you an actual struct_time object
h = t.tm_hour # gives you the hour part as an integer
print(h)

You can do it in one step if that's all you need the hour for:

如果您只需要一小时的时间,您可以一步完成:

print(time.localtime().tm_hour)

回答by dawg

You can use datetime:

您可以使用日期时间

>>> import datetime as dt
>>> dt.datetime.now().hour
9

Or, rather than now() you can use today():

或者,您可以使用 today() 而不是 now():

>>> dt.datetime.today().hour
9

Then insert into any string desired:

然后插入所需的任何字符串:

>>> print('The hour is {} o\'clock'.format(dt.datetime.today().hour))
The hour is 9 o'clock

Note that datetime.today()and datetime.now()are both using your computer's notion of local time zone (ie, a 'naive' datetime object).

请注意,datetime.today()datetime.now()都使用您计算机的本地时区概念(即“天真的”日期时间对象)。

If you want to use time zone info, it is not so trivial. You can either be on Python 3.2+ and use datetime.timezone or use the third party pytz. I am assuming your computer's timezone is fine, and a naive (non time zone datetime object) is fairly easy to use.

如果你想使用时区信息,这不是那么简单。您可以使用 Python 3.2+ 并使用 datetime.timezone 或使用第三方pytz。我假设您的计算机的时区很好,并且一个简单的(非时区 datetime 对象)相当容易使用。