Python How to Convert datetime to String Easily
strftime method of a datetime object with a format string, like datetime_obj.strftime('%Y-%m-%d %H:%M:%S'), to convert datetime to string in Python.Examples
How to Think About It
strftime method, which lets you pick a pattern for the output, like year-month-day or hour:minute:second. This method turns the datetime into a readable string.Algorithm
Code
from datetime import datetime # Create a datetime object now = datetime(2024, 6, 1, 15, 30, 45) # Convert datetime to string string_date = now.strftime('%Y-%m-%d %H:%M:%S') print(string_date)
Dry Run
Let's trace converting datetime(2024, 6, 1, 15, 30, 45) to string.
Create datetime object
now = datetime(2024, 6, 1, 15, 30, 45)
Call strftime with format
string_date = now.strftime('%Y-%m-%d %H:%M:%S')
Print the string
Output: '2024-06-01 15:30:45'
| Step | Action | Value |
|---|---|---|
| 1 | Create datetime | 2024-06-01 15:30:45 |
| 2 | Convert to string | '2024-06-01 15:30:45' |
| 3 | Print output | 2024-06-01 15:30:45 |
Why This Works
Step 1: Using strftime method
The strftime method formats the datetime object into a string based on the format codes you provide.
Step 2: Format codes define output
Codes like %Y for year and %m for month tell Python how to build the string.
Step 3: Result is a string
The method returns a string that represents the datetime in the format you chose.
Alternative Approaches
from datetime import datetime now = datetime(2024, 6, 1, 15, 30, 45) string_date = now.isoformat() print(string_date)
from datetime import datetime now = datetime(2024, 6, 1, 15, 30, 45) string_date = str(now) print(string_date)
Complexity: O(1) time, O(1) space
Time Complexity
Converting datetime to string with strftime is a fixed-time operation, so it runs in constant time.
Space Complexity
The operation creates a new string, so space used is proportional to the length of the output string, which is constant for fixed formats.
Which Approach is Fastest?
strftime and isoformat are both very fast; str() is simplest but less flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| strftime | O(1) | O(1) | Custom date/time string formats |
| isoformat | O(1) | O(1) | Standard ISO 8601 format |
| str() | O(1) | O(1) | Quick default string conversion |
strftime with format codes to get exactly the string format you want.strftime and trying to convert datetime directly with str() expecting a custom format.