Skip to content

Instantly share code, notes, and snippets.

@caglartoklu
Created February 25, 2013 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caglartoklu/5029647 to your computer and use it in GitHub Desktop.
Save caglartoklu/5029647 to your computer and use it in GitHub Desktop.
Returns string representation of datetime objects. #python #datetime
import datetime
def get_datetimestamp(sep_date="", sep_group="_", sep_time="", moment=None):
"""
Returns string representation of datetime objects.
By default, the value will look like "20121212_120102" and it
is safe to use it on file names.
sep_date:
string, separator between year, month and day
sep_group:
string, separator between the date and time.
sep_time:
string, separator between hour, minute and second
moment:
an instance of datetime.datetime.
if it is None(the default), now() will be used.
Requires:
import datetime
>>> import datetime
>>> some_date = datetime.datetime(2012, 12, 12, 12, 1, 2)
>>> print get_datetimestamp(moment=some_date)
20121212_120102
>>> print get_datetimestamp(sep_date="/", sep_group="-", moment=some_date)
2012/12/12-120102
>>> print get_datetimestamp(sep_group="-", sep_time=":", moment=some_date)
20121212-12:01:02
"""
date_format = (sep_date.join(["%Y", "%m", "%d"]) +
sep_group +
sep_time.join(["%H", "%M", "%S"]))
if moment is None:
moment = datetime.datetime.now()
stamp = moment.strftime(date_format)
return stamp
def apply_doctest():
"""
Applies the doctest to the module.
http://docs.python.org/2/library/doctest.html
"""
import doctest
doctest.testmod()
if __name__ == "__main__":
apply_doctest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment