Table of Contents
Python offers us easy-to-use functions inside the datetime
and time
modules to manipulate, convert, and display dates and time.
Python makes working with dates easy.
Getting the Date
We can use the datetime
module to get the exact date and time at the point of running the program:
PYTHONimport datetime
now = datetime.datetime.now()
print(now)
BASH2019-12-01 00:00:00.000000
Getting Information from the Date
Once you have a date project, you can get specific pieces of information out of it by accessing the properties, like so:
PYTHONimport datetime
now = datetime.datetime.now()
day = now.day
month = now.month
year = now.year
print("Day: " + str(day))
print("Month: " + str(month))
print("Year: " + str(year))
BASHDay: 1
Month: 12
Year: 2019
Creating a Date
We can create a new date object by using the datetime
function and passing in the values we want:
PYTHONimport datetime
future = datetime.datetime(2030, 6, 18)
day = future.day
month = future.month
year = future.year
print("Day: " + str(day))
print("Month: " + str(month))
print("Year: " + str(year))
BASHDay: 18
Month: 6
Year: 2030
Formatting a Date
Once you get or create your date object, you can print it out in a readable format using the strftime
function:
PYTHONimport datetime
future = datetime.datetime(2030, 6, 18)
print(future.strftime("%A"))
BASHTuesday
Curious about that %A
? Here are all the other symbols you can use to format your string:
%a
: Weekday (short)%A
: Weekday (full)%w
: Weekday (number)%d
: Day of Month%b
: Month (short)%B
: Month (full)%m
: Month (number)%y
: Year (short)%Y
: Year (full)%H
: Hour (00-23)%I
: Hour (00-12)%p
: AM/PM%M
: Minute%S
: Second%f
: Microsecond%z
: UTC offset%Z
: Timezone%j
: Day of Year%U
: Week Number (starting from Sunday)%W
: Week Number (starting from Monday)%c
: Local date and time%x
: Local date%X
: Local time
Resources
Leave us a message!
×
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js