Python Date Examples: Date Time Format, Convert String to Datetime

In Python, dates are objects. To use datetime in Python, you need to import datetime module.

from datetime import datetime

Create a date object

d = date(2020, 5, 11)
d = datetime.strptime("2020-5-11", "%d-%m-%Y")

Convert a string to date datetime

2021-01-11 15:36:32 +0800

Convert a string date to a timestamp and vice versa

start_date = "1-1-1980"
d = datetime.strptime(start_date, "%d-%m-%Y")
timestamp = int(datetime.timestamp(d))
date_object = datetime.fromtimestamp(timestamp)

Get current date and timestamp

import time
from datetime import date
ts = time.time()
today =
print("Today is ", today) //Today is 2020-06-17

Print a date in a regular format

from datetime import datetime, date

print"%Y-%m-%d %H:%M")
print any_date_object.strftime('%Y-%m-%d')
print "{:%d-%m-%Y}".format(

Calculate number of days between two dates

date1 = date(2020, 5, 15)
date2 = date(2020, 5, 59)
diff = date2 - date1

Convert datetime to date

The date() method can be used.


Get the last day of a month

Calendar module with monthrange() method can be used to retrieve last day of a month. Calendar allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar.

monthrange() returns weekday of first day of the month and number of days in month, for the specified year and month.

from calendar import monthrange

last_day = monthrange(2020, 2)[1]

Format codes

A reference of all the legal format codes:

%aWeekday, short versionThu
%AWeekday, full versionThursday
%wWeekday as a number 0-6, 0 is Sunday4
%dDay of month 01-3125
%bMonth name, short versionNov
%BMonth name, full versionNovember
%mMonth as a number 01-1210
%yYear, short version, without century19
%YYear, full version2020
%HHour 00-2318
%IHour 00-1207
%MMinute 00-5931
%SSecond 00-5902
%fMicrosecond 000000-999999555544
%zUTC offset+0300
%jDay number of year 001-366263
%UWeek number of year, Sunday as the first day of week, 00-5350
%WWeek number of year, Monday as the first day of week, 00-5326
%cLocal version of date and timeMon Dec 31 17:41:00 2018
%xLocal version of date11/22/20
%XLocal version of time13:50:00
%%A % character%

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.