blob: 2e62aa860949f0866bf43326506637e655491e9e [file] [log] [blame]
xixuan9a8b74a2017-08-08 11:24:16 -07001# Copyright 2017 The Chromium OS 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"""The module contains time-related utility functions.
6
7Please note that suite scheduler use UTC timezone to log/kick off tests.
8"""
9
10import collections
11import datetime
12import pytz
13
14# The format of time string.
15TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
16
17# The format to print a timestamp.
18STR_TIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
19
20# The format for calendar timestamp.
21CALENDAR_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
22
Xixuan Wu6f117e92017-10-27 10:51:58 -070023# The format for stackdriver logging timestamp.
24STACKDRIVER_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
25
xixuan9a8b74a2017-08-08 11:24:16 -070026UTC_TZ = pytz.utc
27PST_TZ = pytz.timezone('America/Los_Angeles')
28
29TimeInfo = collections.namedtuple(
30 'TimeInfo',
31 [
32 'weekday',
33 'hour',
34 ])
35
36
37def utc_now():
38 """Return now() in UTC timezone.
39
40 Returns:
41 a datetime.datetime object representing utc now().
42 """
43 return datetime.datetime.now(UTC_TZ)
44
45
46def pst_now():
47 """Return now() in PST timezone.
48
49 Returns:
50 a datetime.datetime object representing pst now().
51 """
52 return datetime.datetime.now(PST_TZ)
53
54
Xixuan Wu008ee832017-10-12 16:59:34 -070055def convert_time_info(time_info, source_tz=PST_TZ, target_tz=UTC_TZ):
xixuan9a8b74a2017-08-08 11:24:16 -070056 """Convert (day, hour) extracted from config file to UTC timezone.
57
58 The time_info could be in any timezone, which is indicated by source_tz.
59
60 Args:
61 time_info: a TimeInfo object including weekday & hour. Weekday is 0~6,
62 hour is 0~23.
63 source_tz: a pytz timezone object, specifies the original timezone to
64 be converted. Default is PST.
Xixuan Wu008ee832017-10-12 16:59:34 -070065 target_tz: a pytz timezone object, specifies the target timezone to be
66 be converted to. Default is UTC.
xixuan9a8b74a2017-08-08 11:24:16 -070067
68 Returns:
69 A UTC TimeInfo object.
70 """
71 source_now = datetime.datetime.now(source_tz)
72 utc_time = source_tz.localize(
73 datetime.datetime(source_now.year, source_now.month,
Xixuan Wu008ee832017-10-12 16:59:34 -070074 source_now.day, time_info.hour)).astimezone(target_tz)
xixuan9a8b74a2017-08-08 11:24:16 -070075 weekday = time_info.weekday
76 if weekday is not None and utc_time.weekday() != source_now.weekday():
77 weekday = (weekday + utc_time.weekday() - source_now.weekday()) % 7
78
79 return TimeInfo(weekday, utc_time.hour)