20.06.2018

Printing dates in Python with the datetime module

Printing dates in Python with the datetime module - Today we are going to dive into the datetime module. The datetime module is useful if you want to know the current time or make time calculations. In the below example we are creating some different time examples. I also created a thread so that we can terminate the execution with any keypress.

#! python3

import datetime
import time
import threading

def input_thread(my_input_list):
    input()
    my_input_list.append("I detect key presses")


def my_date_time_ticker():
    my_input_list = []
    threading.Thread(target=input_thread, args = (my_input_list,)).start()
        
    while True:
        if my_input_list: break
        time_now = str(datetime.datetime.now())
        year = datetime.date.today().strftime("%Y")
        month = datetime.date.today().strftime("%B")
        week_nr = datetime.date.today().strftime("%W")
        weekday = datetime.date.today().strftime("%A")
        week_day_nr = datetime.date.today().strftime("%w")
        day_nr_of_year = datetime.date.today().strftime("%j")
        day_nr_of_month = datetime.date.today().strftime("%d")
        print("Press any key to exit")
        print("Todays date is:", datetime.date.today())
        print("The exact time now is" , time_now)
        print("The current year is" , year)
        print("The current month is" , month)
        print("Day number  of year:", day_nr_of_year)
        print("Day number of month:", day_nr_of_month)
        print("The current week number is:" , week_nr)
        print ("Today is" , weekday, "which has the weekday number of:" , week_day_nr)
        print()
        time.sleep(1)
    
if __name__ == "__main__":
    my_date_time_ticker()
    print("Program terminated")

Happy coding! Do you have some better way to show times in Python? Tell me all about it!

Leave a Reply

Your email address will not be published.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram