Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a short date string back to a DateTime object?

I have 2 DateTime objects, which I save to a file after using the ToShortDateString() function; the strings look like "12/15/2009". I am stuck on this part now, I want to initialize DateTime object(s) with these strings so I can compare the timespan between the date dates. Any help appreciated.

like image 501
IaskQuestions Avatar asked Dec 15 '09 07:12

IaskQuestions


People also ask

How do I convert a string to a datetime object in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do you convert a date to a date object in Python?

Strptime() The strptime() method takes the date as an input and converts it into a date object.

How do I convert a string to a timestamp in python?

Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.


2 Answers

You can try

DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);

Have a look at

like image 186
Adriaan Stander Avatar answered Oct 13 '22 00:10

Adriaan Stander


Assuming you're reading back the dates from the file in string format

string date1 = "28/12/2009"; //this will be from your file
string date2 = "29/12/2009"; //this will be from your file
DateTime d1 = DateTime.ParseExact(date1,"dd/MM/yyyy", null);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", null);
TimeSpan t1 = d2.Subtract(d1);
like image 32
Kamal Avatar answered Oct 13 '22 00:10

Kamal