Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into datetime.time object

Given the string in this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes.

I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that?

like image 662
Zed Avatar asked Jan 12 '13 17:01

Zed


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do you create a datetime object in Python?

To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.

How do I convert a string to a datetime in Salesforce?

Datetime dt = DateTime. parse('10/14/2011 11:46 AM'); String myDtString = dt. format(); system. assertEquals(myDtString, '10/14/2011 11:46 AM');

How to convert a string to a DateTime object in Java?

Let's use the strptime () method to convert a given string to a datetime object, as shown below: If the date string is changed to 'DD-MM-YY', the format has to be set to %d-%m-%Y.

How do I get the date and time of a string?

This example uses the strptime () function of the datetime module. This function takes the date string (month, day, and year) as input and returns it as a datetime object. The previous Python code has created a new datetime object containing the date and time of our input string.

How to convert string to datetime with timezone in Python?

The pd.to_datetime (dt) method is used to convert the string datetime into a datetime object using pandas in python. To get the output as datetime object print (pd.to_datetime (dt)) is used. You can refer the below screenshot for the output: Now, we can see how to convert a string to datetime with timezone in python.

How to convert the string datetime to a DateTime object using PANDAS?

The pd.to_datetime(dt) method is used to convert the string datetime into a datetime object using pandas in python. Example: import pandas as pd dt = ['21-12-2020 8:40:00 Am'] print(pd.to_datetime(dt)) print(dt)


2 Answers

Use datetime.datetime.strptime() and call .time() on the result:

>>> datetime.datetime.strptime('03:55', '%H:%M').time() datetime.time(3, 55) 

The first argument to .strptime() is the string to parse, the second is the expected format.

like image 93
Martijn Pieters Avatar answered Oct 11 '22 21:10

Martijn Pieters


>>> datetime.time(*map(int, '03:55'.split(':'))) datetime.time(3, 55) 
like image 28
Andreas Jung Avatar answered Oct 11 '22 21:10

Andreas Jung