Python Tricks | Towards AI

DateTime Manipulations with Python

Bindhu Balu
Sep 5 · 6 min read

Python DateTime, TimeDelta, Strftime(Format) with Examples

In Python, date, time and DateTime classes provide a number of functions to deal with dates, times and time intervals. Date and DateTime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. Whenever you manipulate dates or times, you need to import DateTime function.

The DateTime classes in Python are categorized mainly into 5 classes.

  • date — Manipulate just date ( Month, day, year)
  • time — Time independent of the day (Hour, minute, second, microsecond)
  • DateTime — Combination of time and date (Month, day, year, hour, second, microsecond)
  • time delta — A duration of time used for manipulating dates
  • tzinfo — An abstract class for dealing with time zones

Step 1) Before you run the code for DateTime, it is important that you import the date-time modules as shown in the screenshot below.

These import statements are pre-defined pieces of functionality in the Python library that lets you to manipulate dates and times, without writing any code.

Step 2) Next, we create an instance of the date object.

Step 3) Next, we print the date and run the code.

Print Date using date.today()

date.today function has several properties associated with it. We can print individual day/month/year and many other things

Let’s see an example

Python Current Date and Time: now() today()

Step 1) Like Date Objects, we can also use “DATETIME OBJECTS” in Python. It gives date along with time in hours, minutes, seconds and milliseconds.

Step 2) With “DATETIME OBJECT”, you can also call time class.

Suppose we want to print just the current time without the date.

Step 3) We will apply our weekday indexer to our weekday’s ArrayList to know which day is today

  • Weekday's operator (wd) is assigned the number from (0–6) number depending on what the current weekday is. Here we declared the array of the list for days (Mon, Tue, Wed…Sun).
  • Use that index value to know which day it is. In our case, it is #0, and it represents Monday, so in the output, it will print out “Which is a Monday.”

How to Format Date and Time Output with Strftime()

As of now, we have learned, how to use DateTime and Date objects in Python. We will advance a step further and learn how to use a formatting function to format Time and Date.

Step 1) First we will see a simple step of how to format the year. It is better to understand with an example.

  • We used the “strftime function” for formatting.
  • This function uses a different control code to give an output.
  • Each control code resembles different parameters like year, month, weekday and date [(%y/%Y — Year), (%a/%A- weekday), (%b/%B- month), (%d — day of month)].
  • In our case, it is (“%Y”) which resembles year, it prints out the full year with the century (e.g., 2018).

Step 2) Now if you replace (“%Y”) with lowercase, i.e., ( “%y) and execute the code the output will display only (18) and not (2018). The century of the year will not display as shown in the screenshot below

Step 3) Strf function can declare the date, day, month and year separately. Also with small changes in the control code in strftime function, you can format the style of the text.

Inside the strftime function if you replace (%a) with capital A, i.e., (%A) the output will print out as “Friday” instead of just an abbreviation “Fri”.

Step 4) With the help of “strftime” function we can also retrieve local system time, date or both.

  1. %C- indicates the local date and time
  2. %x- indicates the local date
  3. %X- indicates the local time

Step 5) The “strftime function” allows you to call the time in either 24 hours format or 12 hours format.

How to use Timedelta Objects

With timedelta objects, you can estimate the time for both the future and the past. In other words, it is a timespan to predict any special day, date or time.

Remember this function is not for printing out the time or date, but something to CALCULATE about the future or past. Let’s see an example to understand it better.

Step 1) To run Timedelta Objects, you need to declare the import statement first and then execute the code

Step 2) Let’s get today’s date and time to check whether our import statement is working well. When code is executed, it prints out today’s date which means our import statement is working well

Step 3) We will see how we can retrieve date a year from now() through delta objects. When we run the code, it gives the output as expected.

Step 4) Another example of how time delta can be used to calculate the future date from the current date and time

Step 5) Let’s look into a more complex example. I would like to determine how many days past the New Year. Here is how we will proceed

  • Using today= date.today() we will get today’s date
  • We know the new year is always on 1-Jan, but the year could be different. Using nyd= date(today.year,1,1) we store the new year in variable nyd
  • if nyd < today: compares whether the current date is greater than the new year. If yes, it enters the while loop
  • ((today-nyd).days) gives the difference between the current date and new year in DAYS

Summary

For manipulating dates and times in both simple and complex ways, DateTime module supplies different classes or categories like

  • date — Manipulate just date ( Month, day, year)
  • time — Time independent of the day (Hour, minute, second, microsecond)
  • DateTime — Combination of time and date (Month, day, year, hour, second, microsecond)
  • timedelta — A duration of time used for manipulating dates
  • tzinfo — An abstract class for dealing with timezones

Using DateTime objects

  • Importing DateTime objects before executing the code is mandatory
  • Using date.today function for printing individual date/month/year as well as indexing the day
  • Using date.time object to get time in hours, minutes, seconds and milliseconds

Formatting Time-Out with “strftime function”

  • Use “strftime function” to change the format of the year
  • Print day, date, month and year separately,
  • Call out time for any format 12 hrs or 24 hrs

Timedelta Objects

  • With timedelta objects, you can estimate the time for both the future and the past
  • Calculate the total days left for the special day(birthday) from the current time
  • Calculate the total days passed for a special day(birthday) from the current time

The Jupyter file for the above codes are available in this link:

https://github.com/BindhuVinodh/Datemanipulationswithpython

Towards AI

Towards AI, is the world’s fastest-growing AI community for learning, programming, building and implementing AI.

Bindhu Balu

Written by

Student of Data Science , Amateur Writer , Mom , loves travelling and learning.

Towards AI

Towards AI, is the world’s fastest-growing AI community for learning, programming, building and implementing AI.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade