|
| 1 | +# Copyright (C) 2018 Google Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Simple time utilities Fire CLI. |
| 16 | +
|
| 17 | +This example demonstrates exposing simple time helper functions using Fire. |
| 18 | +Fire() is called with no target component so all functions in this module |
| 19 | +become CLI commands. |
| 20 | +
|
| 21 | +Example usage: |
| 22 | + time_tools now |
| 23 | + time_tools to-seconds 1 30 |
| 24 | + time_tools add-seconds "2024-01-01 10:00:00" 120 |
| 25 | +""" |
| 26 | + |
| 27 | +import fire |
| 28 | +import datetime |
| 29 | + |
| 30 | + |
| 31 | +def now(): |
| 32 | + """Return the current datetime as a string.""" |
| 33 | + return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 34 | + |
| 35 | + |
| 36 | +def to_seconds(minutes=0, seconds=0): |
| 37 | + """Return minutes + seconds converted to total seconds.""" |
| 38 | + return minutes * 60 + seconds |
| 39 | + |
| 40 | + |
| 41 | +def add_seconds(time_string="", seconds=0): |
| 42 | + """Add seconds to a datetime string.""" |
| 43 | + dt = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") |
| 44 | + new_dt = dt + datetime.timedelta(seconds=seconds) |
| 45 | + return new_dt.strftime("%Y-%m-%d %H:%M:%S") |
| 46 | + |
| 47 | + |
| 48 | +def main(): |
| 49 | + fire.Fire(name="time_tools") |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + main() |
0 commit comments