Jimmy
Jimmy

Reputation: 12487

Save date time in filename with valid chars

To keep track of my when my files were backed up I want to have the filename of the backups as the datetime of when they were backed up. This will eventually be sorted and retrieved and sorted using python to allow me to get the most recent file based on the datetime filename.

The problem is, the automatic format of date time cant be saved like this:

2007-12-31 22:29:59

It can for example be saved like this:

2007-12-31 22-29-59

What is the best way to format the datetime so that I can easily sort by datetime on the name, and for bonus points, what is the python to show the datetime in that way.

Upvotes: 1

Views: 3597

Answers (1)

Vincenzo Pii
Vincenzo Pii

Reputation: 19805

You should have a look the documentation of the python time module: http://docs.python.org/2/library/time.html#module-time

If you go to the strftime() function, you will see that it accepts a string as input, which describes the format of the string you want to get as the return value.

Example (with hyphens between each date/time token):

>>> s = time.strftime('%Y-%m-%d-%H-%M-%S')
>>> print s
2012-12-08-14-55-44

The documentation contains a complete table of directives you can use to get different tokens.

What is the best way to format the datetime so that I can easily sort by datetime?

If you want to sort files according to datetimes names, you can consider that a biggest-to-lowest time specifier representation of a datetime (e.g.: YYYYMMDDhhmmss) preserves the same chronological and lexicographical order.

Upvotes: 4

Related Questions