TRex
TRex

Reputation: 495

How do I convert my date into a slightly different format

date = '9/4/2020'.

Now on excel I converted using the format TEXT(date,'YYYYMMDD'), how do I replicate the same in python?

I tried using the datetime function

d = datetime.strptime(date, '%Y%m%d')

but I get the value error ValueError: time data '9/4/2020' does not match format '%Y%m%d'

how do I fix this?

Upvotes: 0

Views: 173

Answers (4)

Josh Friedlander
Josh Friedlander

Reputation: 11657

In Python this is called strptime (string parse time, ie get time object from a string) and strftime (string from time, get a string representation from a time object - the reverse process).

The various time symbols are listed in the Python dcoumentation here. You need to describe the way the time is formatted exactly, including the separators (such as / or -). In between, you denote year, month,day, etc. according to the code in the docs. So in your case:

d = datetime.strptime(date, '%d/%M/%Y')

Would get you the time object, and then you could use

print(datetime.strftime(d, '%Y%M%d'))

to get the new one.

Or in one line:

d = strftime(strptime('9/4/2020', '%d/%M/%Y'), '%Y%M%d')

should work. (Assuming day comes first.)

Upvotes: 0

BenjaminK
BenjaminK

Reputation: 783

This should do what you want:

d = datetime.strptime(date, '%d/%M/%Y')  # Convert string to date
new_date_format = d.strftime("%Y%m%d")  # Set your custom date format
print('My new Date format: {}'.format(new_date_format)). # Print the result

Upvotes: 0

nimrodz
nimrodz

Reputation: 1594

first you need to use lower case m in the format. after converting to datetime, just convert back to string using strftime

d = datetime.strptime(date, '%d/%m/%Y').strftime('%Y%m%d')

another option is just split the string date:

f"{date.split('/')[2]}{date.split('/')[1].zfill(2)}{date.split('/')[0].zfill(2)}"

'20200409'

Upvotes: 0

Anshul Vyas
Anshul Vyas

Reputation: 663

Not sure if you want output like this:

date = '9/4/2020'
d = datetime.datetime.strptime(date, '%d/%M/%Y')
print(d)

Output:

2020-01-09 00:04:00

Upvotes: 1

Related Questions