Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am required to extract the time of the day from the datetime.datetime object returned by the created_at attribute, but how can I do that?

This is my code for getting the datetime.datetime object.

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.

like image 430
Abhishek Sharma Avatar asked Sep 09 '14 22:09

Abhishek Sharma


People also ask

How do I get hours and minutes from datetime?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do you pull hours from datetime?

To extract time only from datetime with formula, you just need to do as follow: 1. Select a blank cell, and type this formula =TIME(HOUR(A1),MINUTE(A1), SECOND(A1)) (A1 is the first cell of the list you want to extract time from), press Enter button and drag the fill handle to fill range.


2 Answers

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

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

for example.

like image 94
afrendeiro Avatar answered Sep 19 '22 13:09

afrendeiro


If the time is 11:03, then afrendeiro's answer will print 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:

str(tdate.time())[0:5] 
like image 31
shaneb Avatar answered Sep 22 '22 13:09

shaneb