Python Lesson 17: Date & Time Manipulation in Python

Advertisements

Hello everybody,

Michael here, and today’s lesson will be on performing date & time manipulation in Python. Now I know I did a date & time manipulation lesson in R (check out R Lesson 19: Fun With Dates & Times), but I want to show you how it’s done in Python.

Before I get started with any coding examples, I think it will be important to mention that dates aren’t data types. However, we can import a datetime module to create date & time objects; to import the datetime module, use the line import datetime.

Now, here’s how to use the datetime module to display the current date and time:


now = datetime.datetime.now()

print(now)

2021-04-15 22:16:45.356841

In this example, I created a datetime object-now-that displays the current date and time (using the 24-hour format for time) using the datetime.now() method of the datetime module. Simple enough, right?

Well, along with displaying the current date & time, the datetime module also has several format codes to retrieve information about a datetime object. Let’s say we wanted to retrieve the current month (fully spelled out) and the current day of the week (in shorthand). Here’s how to do so:

now = datetime.datetime.now()

print(now.strftime("%a"))
print(now.strftime("%B"))

Thu
April

In this example, I am retrieving the current day of the week (in shorthand) and the current month (fully spelled out) from the current datetime-April 15, 2021 10:16:45PM. To retrieve the shorthand day of the week, I used the format code %a and to retrieve the fully spelled out month, I used the format code %B. Also, in order to use these format codes, I need to use them as parameters in the function strftime.

Here’s a list of all the format codes you can use with the strftime function (all examples refer to the now object):

  • %a-returns the shorthand version of the weekday.
    • example: %a would return Thu (which is shorthand for Thursday)
  • %A-returns the fully spelled out version of the weekday
    • example: %A would return Thursday (the name of the weekday spelled out)
  • %w-returns the corresponding number of the weekday; the weekdays are numbered from 0-6, with 0 being Sunday and 6 being Saturday
    • example: %w would return 4 (Thursday corresponds to 4)
  • %d-returns the day of the month (which can range from 01-31)
    • example: %d would return 15 (the day of the month in the now object is 15)
  • %b-returns the shorthand version of the month
    • example: %b would return Apr since the month for the now object is April.
  • %B-returns the fully spelled out version of the month
    • example: %B would return April (which is the month for the now object)
  • %m-returns the number of the month (which can range from 01 to 12):
    • example: %m would return 04 since April is the 4th month of the year
  • %y-returns the last two digits of the year:
    • example: %y would return 21 since the year is 2021
  • %Y-returns the full version of the year:
    • example: %Y would return 2021 since the year is 2021
  • %H-returns the hour according to a 24-hour clock:
    • example: %H would return 22 since the time is 10:16 PM.
  • %I-returns the hour according to a 12-hour clock:
    • example: %I would return 10 since the time is 10:16 PM.
  • %p-returns AM or PM depending on whether the time is before or after 12 noon.
    • example: %p would return PM since the time is 10:16 PM.
  • %M-returns the minute of the time part of the datetime object (ranging from 00-59)
    • example: %M would return 16 since the minute of the time part of now is 16.
  • %S-returns the second of the time part of the datetime object (ranging from 00-59)
    • example: %S would return 45 since the second of the time part of now is 45 (the full time is 10:16:45 PM)
  • %f-returns the millisecond part of the datetime object (ranging from 000000-999999)
    • example: %f would return 356841 since the millisecond part of now is 356841 (the full time with milliseconds is 10:16:45.356841 PM)
  • %z-returns the difference between the current time and UTC time (in hours)
    • example: I know I didn’t set a time-zone for now, but if I did, %z would return -0600 since I’m writing this post from the US Central Time Zone and US CST is 6 hours behind UTC.
  • %Z-returns the time-zone
    • example: %Z would return CST as I’m currently in the US Central Time Zone (this would work if I had set a time zone)
  • %j-returns the day number of the year (ranging from 001-366)
    • example: %j would return 105 as April 15 is the 105th day of the year.
    • An important thing to note here is that if the date for now was set to April 15, 2020, %j would return 106 since April 15 is the 106th day of the year in leap years.
  • %U-returns the week number of the year (ranging from 00-53); this format code assumes weeks start on Sunday
    • example: %U would return 20 as April 15, 2021 falls on the 20th week of the year 2021.
    • The %U format code would return 01 for January 3-9, 2021, as this is the first full week of the year. However, for January 1-2, 2021, %U returns 00. Interestingly, for December 27-31, 2020 (which falls on the same week as January 1-2, 2021), %U would return 52.
  • %W-returns the week number of the year (ranging from 00-53); unlike the format code %U, this format code assumes weeks start on Monday
    • example: %W would also return 20 since it is still the 20th week of the year 2021 (even though %W uses the weeks-starting-on-Monday system)
  • %c-returns the local date and time; the local date and time is displayed using this format-(day of week) (month & day) (local time in 24-hour format) (year)
    • example: %c would return Thu Apr 15 22:16:45 2021 as that is the local time stored in the now object.
    • Only the hours, minutes, and seconds are returned from the local time.
  • %x-returns the date in mm/dd/yy format
    • example: %x would return 04/15/21
  • %X-returns the local time in 24-hour format
    • example: %X would return 22:16:45
  • Just as with regex special sequences, the letter casing can be very easy to mix up between format codes, so keep that in mind.
  • Date format codes start with percent signs while regex special sequences start with backslashes (it can be very easy to confuse date format codes with regex special sequences).

Now, what if I wanted to create my own datetime object? Here’s how to do so:

date1 = datetime.datetime(2021, 4, 18)

print(date1)

2021-04-18 00:00:00

In this example, I created my datetime object date1 and set the parameters equal to 2021, 4, and 18, respectively. When I printed the date1 object, I got the output 2021-04-18 00:00:00.

How did I get this output? Well, since I used 2021, 4, and 18 as parameters, I got the date 2021-04-18 since the year is the first parameter to set when creating a datetime object followed by the month and day.

However, you’re probably wondering how I got the time 00:00:00. See, when I create a datetime object, I can not only set a date but I can also set a time. Aside from the year, month, and day, I can also set an hour, minute, second, millisecond, and time zone parameter. All of these parameters are optional when creating a datetime object, and if no value is specified for each of these parameters, 00 is the default value-hence why the outputted time was 00:00:00.

Now that I’ve shown you the basic things you can do with the datetime package, let’s discuss how to perform date manipulation.

First of all, what if we wanted to calculate the difference between two dates? Here’s how we would do so:

date2 = datetime.datetime(2021, 9, 9)
date3 = datetime.datetime.now()
delta = date2 - date3

print("There are" ,delta.days, "more days until the 2021 NFL season.")
There are 143 more days until the 2021 NFL season.

In this example, I created two datetime objects-date2 and date3-and created a variable delta to determine the difference between the two dates.

  • Just so you know, the date being referenced in now is April 18, 2021. Also, the 2021 NFL season starts on September 9, 2021, hence why the date2 parameters are (2021, 9, 9).

After subtracting the two datetime objects, I then get the message There are 143 more days until the 2021 NFL season. Just for reference, here is the print statement I used: print("There are" ,delta.days, "more days until the 2021 NFL season."). The delta.days statement returns the number of days between the two datetime objects.

Now, what if you wanted to find the amount of weeks between two dates? Here’s how to do so:

date2 = datetime.datetime(2021, 9, 9)
date3 = datetime.datetime(2021, 4, 18)
delta = date2 - date3

print("There are" ,round(delta.days/7, 1), "more weeks until the 2021 NFL season.")

There are 20.6 more weeks until the 2021 NFL season.

Unfortunately, finding the number of weeks between two dates isn’t as simple as using delta.weeks (I know because I tried this). If you want to find the amount of weeks between two dates, simply divide the result of delta.days by 7. The decimal generated by delta.days/7 is quite long, so it’s often useful to round the decimal (using the round function) to either 1 or 2 decimal places as I did above.

Now let’s see how we can get the amount of months between two dates:

date2 = datetime.datetime(2021, 9, 9)
date3 = datetime.datetime(2021, 4, 18)
delta = date2 - date3

print("There are" ,round(delta.days/30, 1), "more months until the 2021 NFL season.")

There are 4.8 more months until the 2021 NFL season.

In this example, I used the same approach to finding the amount of months between two dates as I did when I was trying to find the amount of weeks between two dates (even rounding the quotient to one decimal place). The only difference between this example and the previous example is that I divided delta.days by 30 to find the amount of months between the two dates.

  • You probably guessed this, but there is no delta.months function. Hence why we need to divide the result of delta.days by 30.
  • In order to get the amount of months between two dates, you don’t have to divide delta.days by 30. 28 might work, but when I tried dividing delta.days by 28 in the above example, I got 5.1 (I felt that 4.8 was more accurate).

Now I’ve shown you how to create datetime objects as well as calculate the difference (in days, weeks, and months) between two datetime objects. What if we wanted to find out the date that would be X days before or after a certain date? Here’s how to do so:

from datetime import timedelta

date4 = datetime.datetime.now()

newdate = date4 + timedelta(days=20)

print(newdate)

2021-05-09 22:10:53.372408

In order to add or subtract days from a certain date, I would first need to import the timedelta module from the datetime package (use the line from datetime import timedelta). In this example, I created a datetime object date4 and set it to the current date & time (April 19, 2021 at 10:10 PM). I then created a newdate object and set it equal to the value of date4 plus 20 days from date4 using the timedelta(days=20) function-I then got the result of 2021-05-09 22:10:53.372408.

Now, what if you wanted to subtract 20 days from date4? Here’s how you would do so using the timedelta function:

date4 = datetime.datetime.now()

newdate = date4 - timedelta(days=20)

print(newdate)

2021-03-30 22:20:01.464021

In order to find out the datetime that falls 20 days before date4, all I needed to do was replace the plus sign with a minus sign and VOILA!-I get the new datetime (March 30, 2021 at 10:20 PM).

  • Using this line of code for newdatenewdate = date4 + timedelta(days=-20)-would’ve worked as well.
  • Unfortunately, you can only add or subtract dates with timedelta-multiplying, dividing, or raising dates to a certain power won’t work with timedelta (I know because I tried this and kept getting TypeErrors).

The timedelta function not only calculates days before or after a certain date. You can also calculate weeks, hours, minutes, seconds, milliseconds, and nanoseconds (yes, timedelta is that precise) before or after a certain datetime.

  • There are 1 million nanoseconds in a millisecond, in case you’re wondering.

Thanks for reading,

Michael

Leave a ReplyCancel reply