If I had a date in the format '2016-07-31'
How would I turn it to '2016-07'? I have datetime imported
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With