Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(159)

Side by Side Diff: infra_libs/time_functions/zulu.py

Issue 2213143002: Add infra_libs as a bootstrap dependency. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Removed the ugly import hack Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2015 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
6 """Provides functions for parsing and outputting Zulu time."""
7
8 import datetime
9 import pytz
10
11 from infra_libs.time_functions import timestamp
12
13
14 def parse_zulu_time(string):
15 """Parses a Zulu time string, returning None if unparseable."""
16
17 # Ugh https://bugs.python.org/issue19475.
18 zulu_format = "%Y-%m-%dT%H:%M:%S"
19 if '.' in string:
20 zulu_format += ".%f"
21 zulu_format += "Z"
22 try:
23 return datetime.datetime.strptime(string, zulu_format)
24 except ValueError:
25 return None
26
27
28 def parse_zulu_ts(string):
29 """Parses Zulu time and converts into a timestamp or None."""
30 zuluparse = parse_zulu_time(string)
31 if zuluparse is None:
32 return None
33 return timestamp.utctimestamp(zuluparse)
34
35
36 def to_zulu_string(dt):
37 """Returns a Zulu time string from a datetime.
38
39 Assumes naive datetime objects are in UTC.
40 Ensures the output always has a floating-point number of seconds.
41 """
42
43 # Assume non-tz-aware datetimes are in UTC.
44 if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
45 dt = dt.replace(tzinfo=pytz.UTC)
46
47 # Convert datetime into UTC.
48 isodate = dt.astimezone(pytz.UTC).isoformat().split('+')[0]
49
50 # Add fractional seconds if not present.
51 if '.' not in isodate:
52 isodate += '.0'
53
54 return isodate + 'Z'
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698