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
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
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.
import datetime
my_str = '20170301'
my_date = datetime.datetime.strptime(my_str,'%Y%m%d')
print(my_date)
print(type(my_date))
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'>
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.
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]