Willie Jeovanny
Willie Jeovanny

Reputation: 15

How can I find what time of day it is in python?

what time of day is it ? [morning/afternoon/evening/night]

#example:
a = day()
print("The time is ") + a

Should Output

The time is Morning/evening/afternoon/night

Upvotes: 0

Views: 1291

Answers (2)

Pear
Pear

Reputation: 351

It's kinda easy!

Code:

import datetime as dt

def day(han):       #find what time of day is it?
    t = han.datetime.now()
    h = t.strftime("%H")
    h = int(h)
    if h < 12:
        return "morning"
        h = 0
        t = 0
    if h < 16:
        return "afternoon"
        h = 0
        t = 0
    if h < 19:
        return "evening"
        h = 0
        t = 0
    if h < 24:
        return "night"
        h = 0
        t = 0
    return "midnight"
    h = 0
    t = 0

a = day(dt)
print("The time is " + dt)

Upvotes: 0

Filip
Filip

Reputation: 926

You can use the datetime module for that

from datetime import datetime

def get_time_of_day(time):
    if time < 12:
        return "Morning"
    elif time < 16:
        return "Afternoon"
    elif time < 19:
        return "Evening"
    else:
        return "Night"



now = datetime.now()
print("It's currently:", get_time_of_day(now.hour))

Upvotes: 4

Related Questions