Python datetime With Examples

Python datetime

In this post, we will study about how to use the python datetime module. With datetime module, we can get information about datetime and format dates as well.

Using datetime module

Let’s start working on python datetime module straightaway.

Python datetime now()

It is easy to print current time using datetime module. Let’s see the code snippet on how this can be done:

Let’s see the output for this program:

datetime_current_time

At first, accessing a property inside datetime module which has the same name looks odd. You can call the now() function to print the date information, as shown above. Notice that datetime now() returns the date-time information in a user-friendly way and looks much better than we get from time module.

Python datetime format

Most of the times, single date format do not fulfill our needs in the application. We can format our code using the code snippet we show next:

Let’s see the output for this program:
datetime_format_time
Note that here, the smaller m reflects the Month and capital M shows the minute part for time. This often leads to confusions and is a point to remember.

Python datetime example

We can do a lot more with datetime format like getting the present year, calculating weekday of the day, day of the year, etc. All of this is possible with single calls and we just need to use the strftime() function appropriately. Let’s see the code snippet on how this can be done:

Let’s see the output for this program:
datetime format time
Now that was a lot of information which can be used.

Getting Weekday for a Date

It is also possible to get a weekday for a given date. This is sometimes needed in calendar-based applications or just for curiosity!

Let’s see the code snippet on how this can be done:

Let’s see the output for this program:

datetime format time

Python String to datetime

We can use strptime() function to get datetime object from String. Let’s see a short example for this.

The output of the above program is shown below.

Conclusion

In this post, we saw how we can use the Python datetime module to provide date information and put it to use in our application. It’s a very useful module to provide date and time information in a user-friendly way. Also, there are many functions for formatting and getting specific information. So this module comes very handily in python application dealing with dates.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: