1

My data looks like this and I need to use only the days. How can I split the int YYYYMMDD into three integers YYYY, MM, DD

YYYYMMDD
20170301
20170302
20170303
20170304
20170305
chepner
  • 497,756
  • 71
  • 530
  • 681
G.M.
  • 15
  • 1
  • 4
  • 1
    Possible duplicate of [Python date string to date object](https://stackoverflow.com/questions/2803852/python-date-string-to-date-object) – Patrick Artner Jan 12 '18 at 19:48

3 Answers3

4

Edit: Just noted OP only wanted the day. If you don't care to interpret the string as a datetime object, @chrisz's answer is simpler.

For just the day:

my_date= '20170301'
my_day = int(my_date[-2:])

The [-2:] represents slicing the string, from the second last character to the end, which returns '01', and is then converted to an integer by int().

Original answer:

If you want to interpret the date as a datetime object for other references, use strptime from datetime module.

INPUT:

import datetime
my_str = '20170301'
my_date = datetime.datetime.strptime(my_str,'%Y%m%d')
print(my_date)
print(type(my_date))

OUTPUT:

2017-03-01 00:00:00
<class 'datetime.datetime'>

Now you can interpret the datetime object. You can now grab the year, month, day easily:

my_day = b.day
my_month = b.month
my_year = b.year
print(my_year, my_month, my_day)
print(type(my_year), type(my_month), type(my_day))

Returns:

2017 3 1
<class 'int'> <class 'int'> <class 'int'>
r.ook
  • 13,466
  • 2
  • 22
  • 39
2

You can subscript strings like so, so just convert your int to a string, and do this, and then convert back using int() and str()

data = str(20170305)

year = int(data[0:4])
month = int(data[4:6])
day = int(data[6:8])

print(year, month, day)

Output:

2017 3 5 

If you actually want to convert this into a date object, @Idlehands's answer will help you.

If you just need the day, you can also do:

data = 20170305
day = abs(data) % 100
print(day)

Output:

5

Just note that this will not preserve the DD format, and you would have to account for that.

user3483203
  • 50,081
  • 9
  • 65
  • 94
1

Using a for loop, you could extract year, month, and day, and convert them to integers.

data = ['20170301',
        '20170302',
        '20170303',
        '20170304',
        '20170305']

yyyy_mm_dd = []

for date in data:
    year = int(date[:4])
    month = int(date[4:6])
    day = int(date[6:])
    yyyy_mm_dd.append([year, month, day])

print(yyyy_mm_dd)
# [[2017, 3, 1], [2017, 3, 2], [2017, 3, 3], [2017, 3, 4], [2017, 3, 5]]

Use a list comprehension to extract days from yyyy_mm_dd:

days = [sub[-1] for sub in yyyy_mm_dd]

print(days)
# [1, 2, 3, 4, 5]
srikavineehari
  • 2,502
  • 1
  • 11
  • 21
  • For some resson this is not working and is giving me the following error: ValueError: invalid literal for int() with base 10: '' – G.M. Jan 12 '18 at 21:29
  • @G.M., I think it is due to the string `YYYYMMDD` that you may have included in the data. – srikavineehari Jan 12 '18 at 21:58