How to affiliate papers that I worked on both as a PhD student and as a postdoc? I have submitted my dissertation recently (in mathematics), and I have a position for a postdoc which I will start around October.

In the meantime, one of my friends and I have been working on some projects (some of which we began nearly a year ago), and prepare to write some papers. At least one of them we expect to finish over the summer, and that's fine, there's no hard choices how to affiliate myself there: I'm still considered a student.

But the second paper we have been working on is probably going to take longer than that before we are ready to publish it. So both of us will be moving on from our current university.

How do we decide which affiliation to use when we finally make the paper public? Do we take it as the affiliation at the time, or the one under which we worked the most?

(To clarify, none of our papers are directly related to either of our dissertations.)
This is a mathematics specific answer.  My understanding is that conventions may be different in other fields.

The primary purpose (in mathematics) of the affiliation on your paper is to distinguish you from other people with the same name and to provide a way for readers to contact you.  Therefore, you should put your affiliation at the time the paper is submitted.  Furthermore, if you change affiliations between submitting the paper and getting the paper proofs before final publication (which is likely to happen), you should make the change on the paper so that the published version matches your affiliation at the time.

You can (and in my opinion generally should) acknowledge your former affiliation(s) in an acknowledgement section.