Pyton Datetime
Python Dates
We can import a module named datetime to work with dates as date objects.
Example:
Import the datetime module and print the current date
import datetime x = datetime.datetime.now() print(x)
Output:
2019-05-03 13:11:14.059345
Date Output
The date output contains the year, month, day, hour, minute, second and microsecond. The datetime module has many methods to return information about the date object. Let us try few methods in below example.
Example:
import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A"))
Output:
2019 Tuesday
Creating Date
Objects:
To create a date, we can use the datetime() class (constructor) of the datetime module.. The datetime() class requires three parameters to create a date such as year, month, day. The datetime() class also takes parameters for time and timezone such as hour, minute, second, microsecond and tzone but they are optional, and has a default value of 0 and None for timezone
Example:
import datetime x = datetime.datetime(2020, 5, 17) print(x)
Output:
2020-05-17 00:00:00
Strftime() Method:
To format date objects into readable strings, we use strftime() method which takes one parameter, format, to specify the format of the returned string.
Example:
Display the name of the month:
import datetime x = datetime.datetime(2019, 6, 1) print(x.strftime("%B"))
Output:
June
A reference of all the legal format codes:
Format |
Description |
Example |
%a |
Weekday, short version |
Wed |
%A |
Weekday, full version |
Wednesday |
%w |
Weekday as a number 0-6, 0 is Sunday |
3 |
%d |
Date of month 01-31 |
30 |
%b |
Month name, short version |
Mar |
%B |
Month name, full version |
March |
%m |
Month as a number, 01-12 |
11 |
%y |
Year, short version, without century |
19 |
%Y |
Year, full version |
2019 |
%H |
Hour, 00-23 |
09 |
%I |
Hour, 00-12 |
05 |
%p |
AM/PM |
AM |
%M |
Minute, 00-59 |
45 |
%S |
Second, 00-59 |
43 |
%f |
Microsecond, 000000-999999 |
458134 |
%z |
UTC offset |
+0100 |
%Z |
Timezone |
CST |
%j |
Day number of the year, 001-366 |
364 |
%U |
Week number of the year, Sunday as the first day of the week, 00-53 |
46 |
%W |
Week number of the year, Monday as the first day of the week, 00-53 |
46 |
%c |
Local version of date and time |
Tue May 7 09:21:15 2019 |
%x |
Local version of date |
05/07/2019 |
%X |
Local version of time |
09:21:15 |
%% |
A % character |
% |