I want to add a more theoretical reasoning to @KritikerDerElche's already good answer.
If referring to a time interval, "im" (same as "in der") can be understood as "inside" or "within".
- Im Januar
- Im Jahr 2020
- Im ersten Jahr
- In der zweiten Woche
These are all timespans or intervals. But beginning and end are time points, not interval, so no event can occur in them, only at them.
For the same reason it is very unusual to say "im Anfang" (in the beginning), but rather "am Anfang" (at the beginning).
But as @KritikerDerElche already stated at the end (no pun intended) of his answer: If you are referring not to the timespan, but the concept, then "im Anfang" or "im Ende" are perfectly fine, for example:
"Im Anfang liegt die Kraft" (not a real idiom, I couldn't think of anything better)
Side note: An older version of the Bible says "Im Anfang war das Wort", but newer version now say "Am Anfang war das Wort"