Python DateTime - strptime() FunctionThe strptime stands for string parse time, and this function is part of the datetime module and is used for parsing strings representing time according to a specified format. Syntax To Use the Function
Basic usageExample 1:Here is the basic usage of the strptime() function with the date Program Output: 2022-01-18 00:00:00 Explanation Here, we specified the date and then formatted the string into the datetime object. Example 2:Here is an example of using the strptime to format the date and time Program Output: 2022-01-18 15:30:45 Explanation The string is parsed using the strptime() method with a format string of "%Y-%m-%d %H:%M:%S" for both date and time components. Example 3:The example program handles the AM/PM information by converting the time into 24-hour format. Program Output: 2022-01-18 15:30:45 Explanation This example demonstrates how to parse a string with AM/PM information. The format string "%Y-%m-%d %I:%M:%S %p" matches the structure of the input string. Example 4:Output: 2024-01-18 12:30:00 2023-02-20 08:45:00 Explanation
String to datetime objectHere is a simple example to demonstrate the working of the strptime() function Program Output: 2024-01-18 12:30:45 <class 'datetime.datetime'> Explanation We have used the strptime() function to convert the string date to the original datetime object, specifying the particular format. Considering Various Formats of DateExampleLet us consider the program to consider the code to handle a variety of date string formats. Program Output: 2024-01-18 00:00:00 2024-01-18 00:00:00 2024-01-18 00:00:00 2024-01-18 12:30:00 2024-01-18 12:30:00 Directives
ConclusionIn conclusion, strptime() is a powerful method for converting date and time strings into datetime objects in Python. It provides flexibility through the format string, allowing you to parse a various date and time representations. Next TopicPython get function signature |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India