Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #102746

Re: There has to be a better way to split this string!

From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Newsgroups comp.lang.python
Subject Re: There has to be a better way to split this string!
Date 2016-02-10 01:45 +0000
Message-ID <mailman.10.1455068769.7749.python-list@python.org> (permalink)
References <56BA91B5.5090400@cajuntechie.org>

Show all headers | View raw


On 10 February 2016 at 01:26, Anthony Papillion <anthony@cajuntechie.org> wrote:
> I am using datetime.now() to create a unique version of a filename.
> 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?
>
> Here is the code I'm using:
>
>
>     unprocessed_tag = str(datetime.datetime.now())
>     removed_spaces = unprocessed_tag.split(" ")
>     intermediate_string = removed_spaces[0] + "-" + removed_spaces[1]
>     removed_colons = intermediate_string.split(":")
>     intermediate_string = removed_colons[0] + "-" + removed_colons[1]
> + "-" + removed_colons[2]
>     removed_dots = intermediate_string.split(".")
>     final_string = removed.dots[0] + "-" + removed_dots[1]
>
>     return final_string

Chris' suggestion to use strftime is better but assuming you really
needed to work with the default string then there are easier ways
e.g.:

>>> from datetime import datetime
>>> str(datetime.now()).translate(str.maketrans(': .', '---'))
'2016-02-10-01-44-54-244789'

--
Oscar

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: There has to be a better way to split this string! Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2016-02-10 01:45 +0000

csiph-web