Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Remove day from date in python?

Tags:

python

If I had a date in the format '2016-07-31' How would I turn it to '2016-07'? I have datetime imported

like image 472
bruhsmh Avatar asked Sep 05 '26 07:09

bruhsmh


1 Answers

If you want to use datetime, you can parse the string with strptime and then use string formatting to print just the parts you want:

>>> from datetime import datetime as dt
>>> '{:%Y-%m}'.format(dt.strptime('2016-07-31', '%Y-%m-%d'))
'2016-07'

Although, as zeet points out, if you know your input will be of the form 'YYYY-MM-DD' it's simpler to just slice it:

>>> date = '2016-07-31'
>>> date[:-3]
'2016-07'
>>> date[:date.rfind('-')]
'2016-07'

Still, using strptime will make it easier if you want to support more formats in a generic way.

like image 78
Nathan Vērzemnieks Avatar answered Sep 06 '26 22:09

Nathan Vērzemnieks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!