Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convert date to datetime

Tags:

python

I have following string of date "2018-05-08" and I would like to convert it into the datetime format of python like: "2018-05-08T00:00:00.0000000". I understand I can combine the string like:

> date = "2018-05-08"
> time = "T00:00:00.0000000"
> date+time
'2018-05-08T00:00:00.0000000'

But is there pythonic way of doing it where I can use libraries like datetime?

like image 849
Hannan Avatar asked Sep 09 '26 06:09

Hannan


2 Answers

You can use datetime module like this example:

import datetime 

date = "2018-05-08"
final = datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S.%f')
print(final)

Output:

2018-05-08T00:00:00.000000

For more details visit datetime's documentation

like image 114
Chiheb Nexus Avatar answered Sep 10 '26 18:09

Chiheb Nexus


Use this code

from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())
like image 36
Chandan Kumar Avatar answered Sep 10 '26 18:09

Chandan Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!