F Peracha
F Peracha

Reputation: 19

to find whether its day or night using time() module in python

I started to write

import time
localtime = time.localtime()
print(localtime)

but the localtime gives nine attributes

time.struct_time(tm_year=2018, tm_mon=7, tm_mday=31, tm_hour=22, 
                 tm_min=32, tm_sec=41, tm_wday=1, tm_yday=212, tm_isdst=1)

I want to find whether its am or pm in python by comparing hours:min:sec with the local time. Please suggest

Upvotes: 1

Views: 6317

Answers (1)

paxdiablo
paxdiablo

Reputation: 882136

tm_hour=22

This is the field you're interested in(a), and you can get at the individual fields just by using (e.g., for the hour) localtime.tm_hour.

You can then use it to figure out what part of the day it is, as follows:

0 - 11 -> am, 12 - 23 -> pm

A simple bit of code for this would be:

import time
mytime = time.localtime()
if mytime.tm_hour < 12:
    print ('It is AM')
else:
    print ('It is PM')

For something more airy-fairy (like day and night), the simplest solution would be fixed times like:

0 - 5, 19 - 23 -> night, 6 - 18 -> day

done with:

import time
mytime = time.localtime()
if mytime.tm_hour < 6 or mytime.tm_hour > 18:
    print ('It is night-time')
else:
    print ('It is day-time')

That, of course, depends entirely on how you define day and night since the sun rises and sets at different times in different parts of the world at different times of the year and, in extreme cases of far-north and far-south latitudes, sometimes not for months at a time.


(a) Technically you probably should be using hour, minute and possibly even second, since it can be argued that both midday and midnight are neither ante-meridian nor post-meridian. But we'll go with simpler solutions in the context of this question.

Sample code, ignoring seconds, follows:

import time
mytime = time.localtime()
myhour = mytime.tm_hour
mymin = mytime.tm_min
if myhour == 0 and mymin == 0:
    print('It is midnight')
elif myhour < 12:
    print ('It is AM')
elif myhour == 12 and mymin == 0:
    print('It is noon')
else:
    print ('It is PM')

Upvotes: 5

Related Questions