Python 如何从 datetime.datetime 对象中提取小时和分钟?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25754405/
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-18 23:36:16  来源:igfitidea点击:

How to extract hours and minutes from a datetime.datetime object?

pythondatetimetwittertweepy

提问by Abhishek Sharma

I am required to extract the time of the day from the datetime.datetime object returned by the created_at attribute. But I do not understand how to do that. This is my code for getting the datetime.datetime object.

我需要从 created_at 属性返回的 datetime.datetime 对象中提取一天中的时间。但我不明白该怎么做。这是我获取 datetime.datetime 对象的代码。

from datetime import *
import tweepy

consumer_key = ''
consumer_secret = ''
access_token = '' 
access_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
tweets = tweepy.Cursor(api.home_timeline).items(limit = 2)
t1 = datetime.strptime('Wed Jun 01 12:53:42 +0000 2011','%a %b %d %H:%M:%S +0000 %Y')
for tweet in tweets:
   print (tweet.created_at-t1)
   t1 = tweet.created_at

I need to only extract the hour and minutes from t1.

我只需要从 t1 中提取小时和分钟。

采纳答案by afrendeiro

Don't know how you want to format it, but you can do:

不知道你想如何格式化它,但你可以这样做:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

例如。

回答by Liam Kirsh

datetime has fields hourand minute. So to get the hours and minutes, you would use t1.hourand t1.minute.

日期时间有字段hourminute。因此,要获得小时和分钟,您可以使用t1.hourand t1.minute

However, when you subtract two datetimes, the result is a timedelta, which only has the daysand secondsfields. So you'll need to divide and multiply as necessary to get the numbers you need.

但是,当您减去两个日期时间时,结果是一个 timedelta,它只有daysseconds字段。因此,您需要根据需要进行除法和乘法运算以获得所需的数字。

回答by shaneb

If the time is 11:03, then the accepted answer will print 11:3.

如果时间是11:03,则接受的答案将打印11:3

You could zero-pad the minutes:

你可以零填充分钟:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time()and only take the hour/minute part:

或者换一种方式使用tdate.time(),只取小时/分钟部分:

str(tdate.time())[0:5]

回答by Madelyne Velasco Mite

It's easier to use the timestamp for this things since Tweepy gets both

由于 Tweepy 获得了两者,因此使用时间戳更容易

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))