6

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?

5 Answers 5

8

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

Sign up to request clarification or add additional context in comments.

Comments

3

Use this code

from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())

1 Comment

import date_converter my_datetime = date_converter.date_to_datetime(my_date)
0
from datetime import datetime 
datetime.strftime(datetime.strptime('2018-05-08','%Y-%m-%d'),'%Y-%m-%dT%H:%M:%S.%f')

OUTPUT:

'2018-05-08T00:00:00.000000'

Comments

0
from datetime import datetime
date_as_datetime = datetime.strptime("2018-05-08", '%Y-%m-%d')
date_as_string = date_as_datetime.strftime('%Y-%m-%dT%H:%M:%S')

print(date_as_string)

Out:

'2018-05-08T00:00:00'

See strptime/strftime options here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Comments

0

Yes, you can use the datetime module and the strftime method from that module. Here is an example below if we want to format the current time.

import datetime

current_time = datetime.datetime.now()

formatted_time = datetime.datetime.strftime(current_time, "%Y-%h-%d %H:%m:%S")
print(formatted_time)

Here is the output:

2018-May-08 13:05:16

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.