Skip to content

Commit

Permalink
Assume UTC timezone if not specified (#693)
Browse files Browse the repository at this point in the history
* Assume UTC for _to_datetime when timezone is not specified.

* Move default_tz to days_ago.
  • Loading branch information
drawlerr authored May 23, 2019
1 parent 65b3b02 commit 1a951d5
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions esrally/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# under the License.

import time
from datetime import datetime
from datetime import datetime, timezone


def to_epoch_millis(t):
Expand Down Expand Up @@ -51,19 +51,22 @@ def sleep(seconds):
time.sleep(seconds)


def _to_datetime(val, date_format=None):
def _to_datetime(val, date_format=None, default_tz=None):
if isinstance(val, datetime):
return val
# unix timestamp
elif isinstance(val, float):
return datetime.fromtimestamp(val)
return datetime.fromtimestamp(val, default_tz)
elif isinstance(val, str):
return datetime.strptime(val, date_format)
ret = datetime.strptime(val, date_format)
if ret.tzinfo is None:
ret = ret.replace(tzinfo=default_tz)
return ret
else:
raise TypeError("Cannot convert unrecognized type '%s' with value '%s' to datetime." % (type(val), str(val)))


def days_ago(start_date, end_date, date_format="%d-%m-%Y"):
def days_ago(start_date, end_date, date_format="%d-%m-%Y", default_tz=timezone.utc):
"""
Calculates the difference in days between a start date and an end date.
Expand All @@ -72,10 +75,12 @@ def days_ago(start_date, end_date, date_format="%d-%m-%Y"):
:param end_date: The end date. May be a datetime instance, a unix timestamp or a string representation of a date.
:param date_format: If one or both date values are provided as strings, the date format which is needed for conversion.
Default: "%d-%m-%Y"
:param default_tz: Timezone to use for dates using unix timestamp or not already specified in date_format
Default: timezone.UTC
:return: The difference between start and end date in complete days.
"""
start = _to_datetime(start_date, date_format)
end = _to_datetime(end_date, date_format)
start = _to_datetime(start_date, date_format, default_tz)
end = _to_datetime(end_date, date_format, default_tz)
return (end - start).days


Expand Down

0 comments on commit 1a951d5

Please sign in to comment.