0

I have researched how to do this, but when I print the date and time separately there are other values that appear e.g. 00:00:00 and 1900-01-01.

Code:

import datetime
date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y')
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S')
print(date)
print(time)

Expected Output:

17/12/2018
13:26:09
>>>

Output:

2018-12-17 00:00:00
1900-01-01 13:26:09
>>>

1 Answer 1

1

You can simply use the datetime.date() and datetime.time() functions:

import datetime
date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y')  # this is a datetime
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S')    # this is also a datetime
print(date.date()) # just the date
print(time.time()) # just the time

Output:

2018-12-17   # do date.strftime('%%d/%m/%Y') to create the string representation you want
13:26:09     # default visualisation is same as you want

You create 2 datetime instances - one only by specifying the time, the other buy only specifying the date. The other param is supplied by default.


Alternativly you can use:

date = datetime.datetime.strptime('17/12/2018', '%d/%m/%Y').date()  # date object
time = datetime.datetime.strptime('13:26:09', '%H:%M:%S').time()    # time object 
Sign up to request clarification or add additional context in comments.

1 Comment

@Newbie101 - You can take only the date part from the via datetime.datetime.strptime(...) created date() - it will be displayers with it's default representation - which for me is 2018-12-17 - if you want your special format 17/12/2018 you need to strftime the date() object

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.