0

So i have a column "Date" that holds dates in a 5 digit format. i´m trying to create a new column with the format i want (%Y-%d-%m), but the loop show below just don´t stops.

for u in df["Date"]: df["DateNew"] = datetime.date(1900,1,28) + datetime.timedelta(days=u)

I would appreciate any suggestions.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
C A
  • 13
  • 4
  • How does this "5-digit format" look like? And by "column" you mean pandas DataFrame column? – FObersteiner Feb 25 '21 at 17:15
  • The dates are written in numbers between 42371 and 43475. And, yes, i mean a pandas DF column. Thank you! – C A Feb 25 '21 at 20:32
  • I understand that the 5 digits are certain number of days, so what i tried in the loop was to sum the number of days to the date where "the count started". – C A Feb 25 '21 at 20:37
  • ok this looks like the format `Excel` uses. I've given an answer how to parse them with `pd.to_datetime` here: [Convert Excel style date with pandas](https://stackoverflow.com/a/65460255/10197418). In general, have another look at [ask] and try to come up with a [mre] - you'll get good answers to your problem much quicker. – FObersteiner Feb 26 '21 at 05:46

1 Answers1

0

In datetime you have access to all of the different pieces of date formats. Here are a couple of examples of accessing and printing them out.

newDate = datetime.datetime(date.year, date.month, date.day, 0, 0, 0)
print(mewDate.strftime("%Y-%M-%d"))
Kyle Hurst
  • 252
  • 2
  • 6
  • Thank you for you answer, but this doesnt really answer my question. The problem is that neither pandas nor datetime recognize this 5-digit format, so i need to manually transform the dates. – C A Feb 25 '21 at 20:35
  • from dateutil.parser import parse and then date = parse(date). This works with almost any date format I've thrown at it and converts it to a datetime consumable format. – Kyle Hurst Feb 25 '21 at 21:14