Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #102744 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2016-02-10 12:34 +1100 |
| Last post | 2016-02-10 12:34 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: There has to be a better way to split this string! Chris Angelico <rosuav@gmail.com> - 2016-02-10 12:34 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2016-02-10 12:34 +1100 |
| Subject | Re: There has to be a better way to split this string! |
| Message-ID | <mailman.8.1455068097.7749.python-list@python.org> |
On Wed, Feb 10, 2016 at 12:26 PM, Anthony Papillion
<anthony@cajuntechie.org> wrote:
> I am using datetime.now() to create a unique version of a filename.
First off, be aware that this won't make a unique file name. But if
you're okay with that (deal with collisions somehow), then sure.
> When the final file is named, it will look something like:
>
> myfile-2015-02-09-19-08-45-4223
>
> Notice I'm replacing all of the "."'s, " "'s, and ":"'s returned by
> datetime.now() with "-"'s. I'm doing that using the following code but
> it's freaking ugly and I KNOW there is a better way to do it. I just
> can't seem to think of it right now. Can anyone help? What is the
> "right", or at least, less ugly, way to do this task?
Instead of using str(), use strftime():
>>> now = datetime.datetime.now()
>>> str(now)
'2016-02-10 12:34:26.377701'
>>> now.strftime("%Y-%m-%d-%H-%M-%S-%f")
'2016-02-10-12-34-26-377701'
You could instead use some other format string if you like. Here's your options:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
ChrisA
Back to top | Article view | comp.lang.python
csiph-web