bruhsmh
bruhsmh

Reputation: 341

How to Remove day from date in python?

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

Upvotes: 6

Views: 32830

Answers (5)

SAKET SAKHARE
SAKET SAKHARE

Reputation: 1

if you want to substract current number of days from datetime object, then following code can help

from datetime import date, timedelta 
today = date.today() # datetime.date(2022, 5, 26)
result = today - timedelta(days=today.day) #  datetime.date(2022, 4, 30)

Upvotes: 0

Xinjie Tang
Xinjie Tang

Reputation: 41

For example I get a column named as df['column'] which has a list of values '2010-10-09' and moving on

First Step: turn this column data as type of datetime by using

df['column'] = pd.to_datetime(df['column'])

Second Step: then change the style of this column by using

df['column'] = df['column'].dt.strftime('%Y-%m')

# %Y means year(full), four digits (e.g.2021).
# %y means year(short), only two digits (e.g.21).
# %m means month.

Upvotes: 4

Matt. Stroh
Matt. Stroh

Reputation: 914

the format of "2016-07-31" is called ISO 8601 -format, this is what i recommend to do.

date_str = "2012-04-21"
wanted_format = datetime.strptime(date_str, '%Y-%m-%d').strftime("%Y-%m")

Upvotes: 0

Nathan Vērzemnieks
Nathan Vērzemnieks

Reputation: 5603

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.

Upvotes: 6

Nick Chapman
Nick Chapman

Reputation: 4624

There are several ways to go about this, two ways are:

  1. Assuming your dates are all constant width1 (meaning each date has the same number of digits in it) you can simply do

    day = day[:6]
    
  2. If your dates are not constant width then you can use datetime and you can simply do

    day = datetime.strptime(day, YOUR_FORMAT)
    day = day.strftime("%Y-%m")
    

You can piece together YOUR_FORMAT for your timestamps by looking at the datetime reference here.

Since your example shows a zero padded month it's pretty likely that you can go with option 1.

1You can actually get away with a non-constant width date provided that the year and month always come first and they are constant width.

Upvotes: 1

Related Questions