Skip to content

Instantly share code, notes, and snippets.

@georgerichardson
Created April 17, 2018 21:13
Show Gist options
  • Save georgerichardson/c321061437d97a71c36ecf5d0426038b to your computer and use it in GitHub Desktop.
Save georgerichardson/c321061437d97a71c36ecf5d0426038b to your computer and use it in GitHub Desktop.
Adds timestamp to the end of string. Useful for file names.
from datetime import datetime
def timestamp_string(string, file_ext=True, hidden_file=False):
""" Adds a timestamp to the end of a string in the format
YYYY_MM_DD_hhmm.
Parameters:
string: str
string to be timestamped
file_ext: bool
specifies whether the string has a file extension
hidden_file: bool
specifies whether file starts with '.'
"""
stamp = '_{}'.format(datetime.strftime(datetime.utcnow(), '%Y_%m_%d_%H%M'))
if file_ext:
string = string.split('.')
if hidden_file:
string[1] = string[1] + stamp
else:
string[0] = string[0] + stamp
return '.'.join(string)
else:
return string + stamp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment