| OLD | NEW |
| (Empty) |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. | |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import calendar | |
| 6 from datetime import datetime | |
| 7 from datetime import time | |
| 8 from datetime import timedelta | |
| 9 | |
| 10 import pytz | |
| 11 | |
| 12 | |
| 13 def GetUTCNow(): # pragma: no cover. | |
| 14 """Returns the datetime.utcnow. This is to mock for testing.""" | |
| 15 return datetime.utcnow() | |
| 16 | |
| 17 | |
| 18 def GetUTCNowWithTimezone(): # pragma: no cover. | |
| 19 """Returns datetime.now but in utc timezone. This is to mock for testing.""" | |
| 20 return datetime.now(pytz.utc) | |
| 21 | |
| 22 | |
| 23 def GetUTCNowTimestamp(): # pragma: no cover. | |
| 24 """Returns the timestamp for datetime.utcnow. This is to mock for testing.""" | |
| 25 return calendar.timegm(GetUTCNow().timetuple()) | |
| 26 | |
| 27 | |
| 28 def RemoveMicrosecondsFromDelta(delta): | |
| 29 """Returns a timedelta object without microseconds based on delta.""" | |
| 30 return delta - timedelta(microseconds=delta.microseconds) | |
| 31 | |
| 32 | |
| 33 def FormatTimedelta(delta): | |
| 34 """Returns a string representing the given time delta.""" | |
| 35 if not delta: | |
| 36 return None | |
| 37 hours, remainder = divmod(delta.total_seconds(), 3600) | |
| 38 minutes, seconds = divmod(remainder, 60) | |
| 39 return '%02d:%02d:%02d' % (hours, minutes, seconds) | |
| 40 | |
| 41 | |
| 42 def FormatDatetime(date): | |
| 43 """Returns a string representing the given UTC datetime.""" | |
| 44 if not date: | |
| 45 return None | |
| 46 else: | |
| 47 return date.strftime('%Y-%m-%d %H:%M:%S UTC') | |
| 48 | |
| 49 | |
| 50 def FormatDuration(datetime_start, datetime_end): | |
| 51 """Returns a string representing the given time duration or None.""" | |
| 52 if not datetime_start or not datetime_end: | |
| 53 return None | |
| 54 return FormatTimedelta(datetime_end - datetime_start) | |
| 55 | |
| 56 | |
| 57 def GetDatetimeInTimezone(timezone_name, date_time): | |
| 58 """Returns the datetime.datetime of the given one in the specified timezone. | |
| 59 | |
| 60 Args: | |
| 61 timezone_name (str): The name of any timezone supported by pytz. | |
| 62 date_time (datetime.datetime): The optional datetime to be converted into | |
| 63 the new timezone. | |
| 64 | |
| 65 Returns: | |
| 66 A datetime.datetime of the given one in the specified timezone. | |
| 67 """ | |
| 68 return date_time.astimezone(pytz.timezone(timezone_name)) | |
| OLD | NEW |