1

I have data with the date format as follows:

    date_format = 190410
    year  = 19
    month = 04
    date  = 10

I want to change the date format, to be like this:

date_format = 10-04-2019

How do I solve this problem?

1

2 Answers 2

2
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'

datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.

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

Comments

1

This is what you want(Notice that you have to change your format)

import datetime

date_format = '2019-04-10'

date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')

print(date_time_obj)

Here is an other example

import datetime

date_time_str = '2018-06-29 08:15:27.243860'  
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

print('Date:', date_time_obj.date())  
print('Time:', date_time_obj.time())  
print('Date-time:', date_time_obj)  

You can also do this

from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

print(date)

There are many ways to achieve what you want.

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.