We will use python datetime module for our clock;
We get the current time and separate the time into hour minutes and second.
First get the current time
import datetime
current_time = datetime.datetime.now()
print(current_time)
Get the time in hour, minute and second
current_hour = current_time.hour
current_minute = current_time.minute
current_second = current_time.second
Now got our clock time components. It will be like this
import datetime
current_time = datetime.datetime.now()
hour = current_time.hour
minute = current_time.minute
second = current_time.second
clock_time = f"{hour}:{minute}:{second}"
print(clock_time)
The code will print the time
Now if we loop the program in every second it will show the the updated time in every second
import time
import datetime
while True:
current_time = datetime.datetime.now()
hour = current_time.hour
minute = current_time.minute
second = current_time.second
clock_time = f"{hour}:{minute}:{second}"
print(clock_time)
time.sleep(1)
We have completed the main structure of our digital clock
Now more improvement and applying to pygame
In the program instead of this line
clock_time = f"{hour}:{minute}:{second}"
we will use this
clock_time = f"{hour:02}:{minute:02}:{second:02}"
because it will always show the time in two digit . for example if the current second is 9 it will show 09
Now our complete code
import datetime
import pygame,sys
from pygame.locals import*
pygame.init()
clock=pygame.time.Clock()
screen=pygame.display.set_mode((800,600))
clock_font=pygame.font.Font(pygame.font.get_default_font(), 150)
game_running=True
while game_running:
# It will run 1 frame per second. So the time will update every second
clock.tick(1)
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
current_time = datetime.datetime.now()
hour = current_time.hour
minute = current_time.minute
second = current_time.second
clock_time = f"{hour:02}:{minute:02}:{second:02}"
screen.fill((255,255,255))
clock_text=clock_font.render(clock_time,True,(0,0,0))
screen.blit(clock_text,(100,200))
pygame.display.update()
You can Get this and also more pygame example from github ( 50+ pygame example)