0

Currently I am trying to trim the current date into day, month and year with the following code.

#Code from my local machine
from datetime import datetime
from datetime import timedelta

five_days_ago = datetime.now()-timedelta(days=5)
# result: 2017-07-14 19:52:15.847476

get_date = str(five_days_ago).rpartition(' ')[0]
#result: 2017-07-14

#Extract the day
day = get_date.rpartition('-')[2]
# result: 14

#Extract the year
year = get_date.rpartition('-')[0])
# result: 2017-07 

I am not a Python professional because I grasp this language for a couple of months ago but I want to understand a few things here:

  1. Why did I receive this 2017-07 if str.rpartition() is supposed to separate a string once you have declared some sort separator (-, /, " ")? I was expecting to receive 2017...
  2. Is there an efficient way to separate day, month and year? I do not want to repeat the same mistakes with my insecure code.

I tried my code in the following tech. setups: local machine with Python 3.5.2 (x64), Python 3.6.1 (x64) and repl.it with Python 3.6.1

Try the code online, copy and paste the line codes

abautista
  • 2,410
  • 5
  • 41
  • 72
  • Possible duplicate of [How to get current time in python and break up into year, month, day, hour, minute?](https://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu) – Dijkgraaf Jul 20 '17 at 01:15
  • Possible but that does not explain question 1. – abautista Jul 20 '17 at 01:16
  • Read rpartition https://python-reference.readthedocs.io/en/latest/docs/str/rpartition.html & partition https://python-reference.readthedocs.io/en/latest/docs/str/partition.html You want partition for the year. Not rpartition – Dijkgraaf Jul 20 '17 at 01:20

1 Answers1

4

Try the following:

from datetime import date, timedelta

five_days_ago = date.today() - timedelta(days=5)
day = five_days_ago.day
year = five_days_ago.year

If what you want is a date (not a date and time), use date instead of datetime. Then, the day and year are simply properties on the date object.

As to your question regarding rpartition, it works by splitting on the rightmost separator (in your case, the hyphen between the month and the day) - that's what the r in rpartition means. So get_date.rpartition('-') returns ['2017-07', '-', '14'].

If you want to persist with your approach, your year code would be made to work if you replace rpartition with partition, e.g.:

year = get_date.partition('-')[0]
# result: 2017

However, there's also a related (better) approach - use split:

parts = get_date.split('-')
year = parts[0]
month = parts[1]
day = parts[2]
Mac
  • 14,615
  • 9
  • 62
  • 80
  • And definitely, I learnt something very valuable today because I thought that .rpartition was the primary tool for splitting strings but I was in such a great mistake. – abautista Jul 20 '17 at 01:29