• Avinash Thakur

Python3: Wanna have a date ? Python has a date and time for you!

Let's see one of the widely used python modules - datetime

A basic example of datetime:

We need to convert the datetime objects to string in the required format so that they can be user-readable. This is how we can do that:

There are following directives which you can use to format the date:

%d - Day of the month (01-31) %m - Month as number (01-12) %b - Short version of month (e.g. Mar) %B - Full version of Month name (e.g. March) %a - Short version of weekday (e.g. Wed) %A - Full version of weekday (e.g. Wednesday)

%w - Weekday as number 0-6 and 0 is Sunday. %Y - Full version of year (e.g 2021)

%y - Short version of year (e.g. 21) %I - Hour ranging 00-12

%H - Hours ranging 00-23 %p - AM/PM %M - Minutes ranging 00-59 %S - Seconds ranging 00-59 %f - Microseconds ranging 000000-999999

%j - Day number of year ranging 001-366

From the frontend we will get the dates as strings to operative over them we will need them to convert to the python's native datetime type.

Let's try some other date format:

Get today's date:

Some examples of datetime.time module to access time and it's conversions:

We often need to calculate date from future or in the past in the real world. Let's how we can calculate that:

Example of timedelta with date objects :

Example of timedelta with time objects :

161 views0 comments

Recent Posts

See All

Django Queries Simplified [Part - 1]

This blog post aims to make django querying simple for the developers who are new in the django world. Keep reading :) What is a django query? A django query is an expression which can be used to writ

Django Queryset with an unusual operation "Merge"

Consider, we have a StudentHistory model defined as: class StudentHistory(models.Model): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=150, b

Python3.6 - What the f-string !

In Python 3.6, there is a new way to format the strings, which helps the user in faster coding, less googling, and better readable code. Which was previously a little tedious by using %-format or even