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 the current date and timestamp
import time
from datetime import date
//timestamp
ts = time.time()
//today
today = date.today()
print("Today is ", today) //Today is 2020-06-17
Print date in a regular format
from datetime import datetime, date
print datetime.now().strftime("%Y-%m-%d %H:%M")
print date.today().strftime("%Y-%m-%d")
print any_date_object.strftime('%Y-%m-%d')
print "{:%d-%m-%Y}".format(datetime.now())
Calculate the number of days between the 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.
<datetime_object>.date()
datetime.datetime.now().date()
Get the last day of a month
Calendar module with monthrange()
method can be used to retrieve the 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 the weekday of the first day of the month and the number of days in a 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:
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Thu |
%A | Weekday, full version | Thursday |
%w | Weekday as a number 0-6, 0 is Sunday | 4 |
%d | Day of month 01-31 | 25 |
%b | Month name, short version | Nov |
%B | Month name, full version | November |
%m | Month as a number 01-12 | 10 |
%y | Year, short version, without century | 19 |
%Y | Year, full version | 2020 |
%H | Hour 00-23 | 18 |
%I | Hour 00-12 | 07 |
%p | AM/PM | AM |
%M | Minute 00-59 | 31 |
%S | Second 00-59 | 02 |
%f | Microsecond 000000-999999 | 555544 |
%z | UTC offset | +0300 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 263 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 50 |
%W | Week number of year, Monday as the first day of week, 00-53 | 26 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%x | Local version of date | 11/22/20 |
%X | Local version of time | 13:50:00 |
%% | A % character | % |