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!
×
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
How to build a Discord bot using TypeScript
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Getting Started with Sass
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Using Push.js to Display Web Browser Notifications
Getting Started with Vuex: Managing State in Vue
How To Create a Modal Popup Box with CSS and JavaScript
Getting Started with Moon.js
