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

前端 未结 4 1397
渐次进展
渐次进展 2020-12-15 02:25

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

相关标签:
4条回答
  • 2020-12-15 03:00

    If the time is 11:03, then the accepted 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]
    
    0 讨论(0)
  • 2020-12-15 03:09

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

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

    for example.

    0 讨论(0)
  • 2020-12-15 03:14

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

    import datetime
    print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
    
    0 讨论(0)
  • 2020-12-15 03:19

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

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

    0 讨论(0)
提交回复
热议问题