0

I've written a fairly long script that organizes data and does some calculations etc, then saves that it all to another excel file in a different location. For the script to run the user enters a date in mmdd form so that it can find the text file with that name to open and run the calculations.

The issue I have comes in at the end when I want to enter the complete date in mm/dd/yy form in the first column of the excel file to keep in line with data from previous years that is already there.

Here is what I have:

mmdd = input("Enter txt file date in mmdd:")
#do a bunch of stuff to get new data
#get the date using mmdd
day = datetime.datetime.strptime(mmdd, '%m%d')
date = day.strftime('%m/%d')
#add data to excel file to new row without any data
row = ws.max_row + 1
new_row = [date, #all other data#]

When I run this it adds mm/dd to the first column no problem. However, I would like to add the current year to the end, i.e. mm/dd/19.

When I use this:

day = datetime.datetime.strptime(mmdd, '%m%d')
date = day.strftime('%m/%d/%y')

I obviously get a garbage year of 1900 because no year was specified in the first place.

I've also tried:

yr = datetime.datetime.now().year

But I can't get it to combine with mm/dd without throwing an error.

Any suggestions would be appreciated.

  • does [this question](https://stackoverflow.com/questions/12468823/python-datetime-setting-fixed-hour-and-minute-after-using-strptime-to-get-day) answer your issue? replacing the year with `now().year`? – Tadhg McDonald-Jensen Dec 10 '19 at 22:04
  • `data = datetime(year=datetime.now().year, month=int(mmdd[:2]), day=int(mmdd[2:]))` – stovfl Dec 10 '19 at 22:18

1 Answers1

0

As suggested by Tadhg, if you use the .replace() method together with .now(), you may get what you intend. Try this:

import datetime

day = datetime.datetime.strptime("1102", '%m%d')
date = day.replace(year=datetime.now().year)
print(date)

You'll get:

2019-11-02 00:00:00
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Kalma
  • 111
  • 2
  • 15