Python DateTime Module with Programs
Python DateTime module with programs

            
              
            

          
        
            Python provides a DateTime module which we'll be using to work with date and time-related cases and also go through the simple program and learn their implementation of this module.


  
  
  Date and Time Functions


The module is packed with a lot of functions. But in this post, we'll be discussing some basic necessary functions.


  
  
  Get Current Date and Time




import datetime

current_date = datetime.datetime.today()
print(current_date)

#PYTHON OUTPUT
datetime.datetime(2020, 2, 26, 12, 59, 32, 944167)   




Here datetime is module name and followed by another DateTime is a class which contains current DateTime information.


  
  
  Creating a new Date and time object




from datetime import datetime
my_datetime = datetime(2020,2,26,1,15,30)
print(my_datetime)

#PYTHON OUTPUT
datetime.datetime(2020, 2, 26, 1, 15, 30)




We have imported datetime class from the module. Class datetime needs parameter through which object is created and
the positional parameters are year,month,day,hour,minute,seconds.

  
  
  Convert String to DateTime object and vice-versa



from datetime import datetime
my_datetime = datetime(2020,2,26,1,15,30)

format = "On %d %B %Y, at %I hour %M minutes and %S seconds %p i saw you in walmart with your brother"
print(my_datetime.strftime(format))

#PYTHON OUTPUT
On 26 February 2020, at 01 hour 15 minutes and 30 seconds AM i saw you in walmart with your brother



format includes those special characters % which will be interpreted to their respective form. Each of those will represent a particular part of date and time.

Let's look and another example were string is converted to DateTime object and again back to the same string which was used as input to class DateTime.


from datetime import datetime

string_datetime = "2020-02-26 8:15:45 PM"
format = "%Y-%m-%d %I:%M:%S %p";
date_obj = datetime.strptime(string_datetime, format)

print("Newly created datetime object : \n")
print(date_obj)

date_object_back_to_string = date_obj.strftime(format)
print("\nConverted datetime object back to string : {}\n".format(date_object_back_to_string));


#PYTHON OUTPUT
python datetime_prog.py 
Newly created datetime object : 

2020-02-26 20:15:45

Converted datetime object back to string : 2020-02-26 08:15:45 PM






strptime(date_string,format) the method takes two arguments they are string representation of DateTime and the format of date-time which is used in this case it is string_datetime.
strftime(format) the method takes one string argument that is in which format the DateTime must be displayed. It converts DateTime object back to a string.

  
  
  Datetime format code table


Python has a standardized format code for representing symbols with respective date and time representation. Some of them are given below.

Symbol Representation 

%a Represents weekday's short name as Mon, Tue.

%A Represents weekday's full name such as Sunday, Monday.

%w Represents weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

%d represents a decimal number of a day like 01, 15 etc

%b Represents month and displays the short name for the month such as for January as Jan, February as Feb

%B Represents months full name

%m Represents numerical name for the month

%Y Represents full 4 characters year number

If you're interested to learn more about DateTime format codes then click here to visit the official site for Python Programming.

  
  
  Python Date and Time programs


  
  
  Show month name from a given date


Program with accepts a date with the day-month-year format and returns the name of a month in a given date.


from datetime import datetime

print("Enter valid date with format (day-month-year) : \n")

input_date = input()

date_object = datetime.strptime(input_date,"%d-%m-%Y")
month = date_object.strftime("%B")

print("Entered date comes in month is : {}".format(month))

#PYTHON OUTPUT
Enter valid date with format (day-month-year) : 

25-03-2020
Entered date comes in month is : March







  
  
  Show number of days in the month


This program takes year and month as input from the user as numeric values convert them into a DateTime object. Another object is created by incrementing month numeric value and if the month goes above 12 than is reassigned to 1 i.e first month.


from datetime import datetime

print("Enter year in format YYYY : \n")
input_year = input()
print("Enter month in number format : \n")
input_month = input()

input_date = "{}-{}".format(input_year,input_month);
format = "%Y-%m"
start_date_obj = datetime.strptime(input_date, format)

if int(input_month) < 12:
    input_month = str(int(input_month)+1)
else: 
    input_month = "1"
    input_year = int(input_year)+1

next_input_date = "{}-{}".format(input_year, input_month)
next_date_obj = datetime.strptime(next_input_date, format)

difference_in_days = (next_date_obj-start_date_obj).days

print("\n***************Output**********************\n")
print("\nYour entered year and month is : {}".format(start_date_obj))
print("\nNext month  : {}".format(next_date_obj))
print("\nDifference in days are : {}".format(difference_in_days))

#PYTHON OUTPUT 1
$ python3.8 datetime_prog.py 
Enter year in format YYYY : 

2020
Enter month in number format : 

1

***************Output**********************


Your entered year and month is : 2020-01-01 00:00:00

Next month  : 2020-02-01 00:00:00

Difference in days are : 31

#PYTHON OUTPUT 2

$ python3.8 datetime_prog.py 
Enter year in format YYYY : 

2020
Enter month in number format : 

2

***************Output**********************


Your entered year and month is : 2020-02-01 00:00:00

Next month  : 2020-03-01 00:00:00

Difference in days are : 29






difference_in_days is calculated by subtracting two different DateTime objects.


  
  
  Show next upcoming month from a given month


Takes month as a number as input from user creates DateTime object and increments the month given by the user with plus 1 which gets us the next month.


from datetime import datetime

print("Enter year in format YYYY : \n")
input_year = input()
print("Enter month in number format : \n")
input_month = input()

input_date = "{}-{}".format(input_year,input_month);
format = "%Y-%m"
start_date_obj = datetime.strptime(input_date, format)

if int(input_month) < 12:
    input_month = str(int(input_month)+1)
else: 
    input_month = "1"
    input_year = int(input_year)+1

next_input_date = "{}-{}".format(input_year, input_month)
next_date_obj = datetime.strptime(next_input_date, format)

difference_in_days = (next_date_obj-start_date_obj).days

print("\n***************Output**********************\n")
print("\nYour entered year and month is : {}".format(start_date_obj))
print("\nNext month  : {}".format(next_date_obj))
print("\nDifference in days are : {}".format(difference_in_days))

#PYTHON OUTPUT 1
$ python3.8 datetime_prog.py 
Enter year in format YYYY : 

2020
Enter month in number format : 

1

***************Output**********************


Your entered year and month is : 2020-01-01 00:00:00

Next month  : 2020-02-01 00:00:00

Difference in days are : 31

#PYTHON OUTPUT 2

$ python3.8 datetime_prog.py 
Enter year in format YYYY : 

2020
Enter month in number format : 

2

***************Output**********************


Your entered year and month is : 2020-02-01 00:00:00

Next month  : 2020-03-01 00:00:00

Difference in days are : 29







  
  
  Conclusion


You have reached at the end of our post on Python DateTime module with programs.we appreciate you for going through this post.
If you find anything difficult with our way of explanation please leave us a comment and if you have enjoyed reading our post.

Click here to read from original post


          