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
- Support Us
Share Post Share
Getting Started with TypeScript
Getting Started with Solid
Managing PHP Dependencies with Composer
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
How To Create a Modal Popup Box with CSS and JavaScript
