• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Lint as: python2, python3
2# Copyright (c) 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6# This module contains some commonly used time conversion function.
7
8from __future__ import absolute_import
9from __future__ import division
10from __future__ import print_function
11
12import datetime
13import six
14import time
15
16
17# This format is used to parse datetime value in MySQL database and should not
18# be modified.
19TIME_FMT = '%Y-%m-%d %H:%M:%S'
20TIME_FMT_MICRO = '%Y-%m-%d %H:%M:%S.%f'
21
22def time_string_to_datetime(time_string, handle_type_error=False):
23    """Convert a string of time to a datetime object.
24
25    The format of date string must match '%Y-%m-%d %H:%M:%S' or
26    '%Y-%m-%d %H:%M:%S.%f'.
27
28    @param time_string: String of date, e.g., 2014-12-05 15:32:45
29    @param handle_type_error: Set to True to prevent the method raise
30            TypeError if given time_string is corrupted. Default is False.
31
32    @return: A datetime object with time of the given date string.
33
34    """
35    try:
36        try:
37            return datetime.datetime.strptime(time_string, TIME_FMT)
38        except ValueError:
39            return datetime.datetime.strptime(time_string, TIME_FMT_MICRO)
40    except TypeError:
41        if handle_type_error:
42            return None
43        else:
44            raise
45
46
47def date_string_to_epoch_time(date_string):
48    """Parse a date time string into seconds since the epoch.
49
50    @param date_string: A string, formatted according to `TIME_FMT`.
51
52    @return The number of seconds since the UNIX epoch, as a float.
53
54    """
55    return time.mktime(time.strptime(date_string, TIME_FMT))
56
57
58def epoch_time_to_date_string(epoch_time, fmt_string=TIME_FMT):
59    """Convert epoch time (float) to a human readable date string.
60
61    @param epoch_time The number of seconds since the UNIX epoch, as
62                      a float.
63    @param fmt_string: A string describing the format of the datetime
64        string output.
65
66    @returns: string formatted in the following way: "yyyy-mm-dd hh:mm:ss"
67    """
68    if epoch_time:
69        return datetime.datetime.fromtimestamp(
70                int(epoch_time)).strftime(fmt_string)
71    return None
72
73
74def to_epoch_time(value):
75    """Convert the given value to epoch time.
76
77    Convert the given value to epoch time if it is a datetime object or a string
78    can be converted to datetime object.
79    If the given value is a number, this function assume the value is a epoch
80    time value, and returns the value itself.
81
82    @param value: A datetime object or a number.
83    @returns: epoch time if value is datetime.datetime,
84              otherwise returns the value.
85    @raise ValueError: If value is not a datetime object or a number.
86    """
87    if isinstance(value, six.string_types):
88        value = time_string_to_datetime(value)
89    if isinstance(value, datetime.datetime):
90        return time.mktime(value.timetuple()) + 0.000001 * value.microsecond
91    if not isinstance(value, int) and not isinstance(value, float):
92        raise ValueError('Value should be a datetime object, string or a '
93                         'number. Unexpected value: %s.' % value)
94    return value
95