How to Split Date and Time in Python?

Estimated read time 2 min read

To split date and time in a string in Python, you can use the datetime module to parse the string into a datetime object, and then use the date() and time() methods to extract the date and time components, respectively. Here’s an example:

import datetime

my_datetime_str = "2022-03-23 12:34:56"
my_datetime = datetime.datetime.strptime(my_datetime_str, '%Y-%m-%d %H:%M:%S')

my_date = my_datetime.date()
my_time = my_datetime.time()

print(my_date)  # Output: 2022-03-23
print(my_time)  # Output: 12:34:56

In this example, we have a string representation of a date and time called my_datetime_str. We use the strptime() method of the datetime module to parse the string into a datetime object. The second argument to strptime() specifies the format of the input string using special codes for each component of the date and time (e.g., %Y for the year, %m for the month, %d for the day, %H for the hour, %M for the minute, and %S for the second).

We then use the date() and time() methods of the datetime object to extract the date and time components, respectively. The date() method returns a date object representing the date component, while the time() method returns a time object representing the time component.

Finally, we print the resulting my_date and my_time objects, which contain the date and time components of the original input string, respectively.

Note that this approach assumes that the input string is in a specific format (YYYY-MM-DD HH:MM:SS). If the input string is in a different format, you may need to modify the format string passed to strptime() to match the input string format.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply