Every programming language required to get a date for development (if required). So how you will get the date in python programming? Python Date Function is provided in a DateTime module, you have to import it.
In this tutorial, you will learn about how to get the current date with the format. Also some examples of getting a year, month, and day of the month.
Syntax
import datetime date = datetime.datetime.now().date()
Python Date Function Example
In this example, you will get a simple date in a year-month-day format.
if must have to import a DateTime module to get a date. Then use a date() or today() function.
import datetime datenow = datetime.datetime.now().date() print('Date', datenow)
Output: Date 2018-10-09
Another Example to get a date
In this example, The date contains the year, month, day, hour, minute, second, and microsecond. By removing .date()
the function you will get all the time and date.
import datetime dateAll = datetime.datetime.now() print('Date', dateAll)
Output: Date 2018-10-09 15:14:35.969381
Get the Year, Month and Day
import datetime dateAll = datetime.datetime.now() print('Year ', dateAll.year) print('Month ', dateAll.month) print('Day ', dateAll.day)
Output: Year 2018
Month 10
Day 9
QA: How to convert datetime to date in Python?
In a python you can convert datetime to date with Use the date()
method:
datetime.datetime.now().date()
See details in the upper part of the tutorial.
Here is also another method to get date form datetime. Using the Python today()
function.
import datetime datenow = datetime.date.today() print('Date ', datenow)
Do comment if you have any doubt and suggestion on this tutorial.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All examples are in Python 3, so it may change its different from python 2 or upgraded versions.