Set datetime Object to Date Only String in Python (3 Examples)
This post explains how to transform a datetime object to date only string in the Python programming language.
Loading datetime Module & Creating Example Data
We have to load the datetime module, as you can see here:
import datetime |
import datetime
The code below generates a data object containing the actual date and time.
x = datetime.datetime.now() print(x) # 2022-03-15 18:03:42.787789 |
x = datetime.datetime.now() print(x) # 2022-03-15 18:03:42.787789
Example 1: Using %s Operator to Return Only Date from datetime Object
To display only the date from a datetime object we can use the %s operator and the month, day, and year attributes:
x_new1 = '%s/%s/%s' % (x.month, x.day, x.year) print(x_new1) # 3/15/2022 |
x_new1 = '%s/%s/%s' % (x.month, x.day, x.year) print(x_new1) # 3/15/2022
Example 2: Using strftime() Function to Return Only Date from datetime Object
The following code shows how to transform a datetime object to a date string using the strftime() function:
x_new2 = x.strftime('%m/%d/%Y') print(x_new2) # 03/15/2022 |
x_new2 = x.strftime('%m/%d/%Y') print(x_new2) # 03/15/2022
The output is the same as in the first example. However, this time, we have used the strftime() function instead of the %s operator.
Example 3: Using date() Function to Return Only Date from datetime Object
In the last example, we’ll use the str() function along with the date() function to get the date in string format:
x_new3 = str(x.date()) print(x_new3) # 2022-03-15 |
x_new3 = str(x.date()) print(x_new3) # 2022-03-15
Further Resources
Please find some related tutorials below.
- Transform datetime Object to Hours Minutes or Seconds in Python (3 Examples)
- Set datetime Object to Local Time Zone in Python (Example)
- All Python Programming Tutorials
Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.