Skip to content

Instantly share code, notes, and snippets.

@toby-p
Last active October 25, 2018 20:35
Show Gist options
  • Select an option

  • Save toby-p/751825670c2549fd3136b0559f0608b3 to your computer and use it in GitHub Desktop.

Select an option

Save toby-p/751825670c2549fd3136b0559f0608b3 to your computer and use it in GitHub Desktop.
Helpful reusable functions for working with datetime objects
import datetime
import pytz
import dateutil
import os
def datetime_to_str(datetime_obj, date_format="%Y_%m_%d_%H_%M_%S"):
"""Convert a `datetime.datetime` object to a string in the desired format.
Reference for string formatting dates available here:
http://strftime.org/
"""
return datetime_obj.strftime(date_format)
def str_to_datetime(str_datetime, date_format=None, **kwargs):
"""Convert a string datetime representation to a `datetime.datetime` object.
If the format is known it can be passed as an argument, e.g. "%d/%m/%Y",
otherwise it will be guessed by `dateutil.parser.parse`, for which kwargs
can be passed.
Reference for string formatting dates available here:
http://strftime.org/
"""
if not date_format:
dt = dateutil.parser.parse(str_datetime, **kwargs)
else:
dt = datetime.datetime.strptime(str_datetime, date_format)
return dt
def formatted_str_now(date_format="%Y_%m_%d_%H_%M_%S", timezone="US/Eastern"):
"""Get a string representation of the current time in the desired format.
Reference for string formatting dates available here:
http://strftime.org/
A list of available timezones can be found by checking `pytz.all_timezones`.
"""
UTC_now = pytz.utc.localize(datetime.datetime.utcnow())
TZ_now = UTC_now.astimezone(pytz.timezone(timezone)).strftime(date_format)
return TZ_now
def get_file_modified_date(fp):
"""Get the datetime stamp of when a file was last modified.
Args:
fp (str): filepath.
"""
unix_time = os.path.getmtime(fp)
return datetime.datetime.fromtimestamp(unix_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment