elisa
elisa

Reputation: 509

How to fix date formatting using python3

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?

Upvotes: 1

Views: 716

Answers (2)

Işık Kaplan
Işık Kaplan

Reputation: 2982

>>> 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.

Upvotes: 2

Iakovos Belonias
Iakovos Belonias

Reputation: 1373

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.

Upvotes: 1

Related Questions