There has to be a better way to split this string!
Oscar Benjamin
oscar.j.benjamin at gmail.com
Tue Feb 9 20:45:42 EST 2016
On 10 February 2016 at 01:26, Anthony Papillion <anthony at 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
More information about the Python-list
mailing list