Python | Convert string to DateTime and vice-versa
Write a Python program to convert a given string to datetime and vice-versa.
Program to convert string to DateTime using strptime() function.
Examples:
Input : Dec 4 2018 10:07AM Output : 2018-12-04 10:07:00 Input : Jun 12 2013 5:30PM Output : 2013-06-12 17:30:00
strptime() is available in datetime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into desired format.
Syntax:
datetime.strptime(date_string, format)
The arguments date_string and format should be of string type.
import datetime # Function to covert string to datetime def convert(date_time): format = '%b %d %Y %I:%M%p' # The format datetime_str = datetime.datetime.strptime(date_time, format) return datetime_str # Driver code date_time = 'Dec 4 2018 10:07AM'print(convert(date_time)) |
Output:
2018-12-04 10:07:00
Program to convert DateTime to string
Examples:
Input : 2018-12-04 10:07:00 Output : Dec 4 2018 10:07:00AM Input : 2013-06-12 17:30:00Jun 12 2013 5:30PM Output : Jun 12 2013 5:30:00PM
Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.
Syntax:
datetime_object.strftime(format_str)
Another similar function is available in time module which converts a tuple or struct_time object to a string as specified by the format argument.
import time # Function to covert string to datetime def convert(datetime_str): datetime_str = time.mktime(datetime_str) format = "%b %d %Y %r" # The format dateTime = time.strftime(format, time.gmtime(datetime_str)) return dateTime # Driver code date_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0) print(convert(date_time)) |
Output:
Dec 04 2018 10:07:00 AM
Recommended Posts:
- Convert the column type from string to datetime format in Pandas dataframe
- Python | Convert String to bytes
- Python | Convert String to Binary
- Python | Convert None to empty string
- Python | Program to convert String to a List
- Python | Convert String to list of tuples
- Python | Convert dictionary object into string
- Python | Convert a list of characters into a string
- Python program to convert hex string to decimal
- Python | Program to convert a tuple to a string
- Python program to convert a list to string
- Python | Convert Bytearray to Hexadecimal String
- Python | Ways to convert string to json object
- Python | Convert tuple records to single string
- Python | Convert byteString key:value pair of dictionary to String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



