I have an .yml
file which is my config. In this file I have defined two times which look like this:
my-times:
earliest_time: 17:00 #PM
latest_time: 19:00 #PM
My code looks like this:
conf: object = yaml.safe_load(open('myconfig.yml'))
earliest_time = str(conf['my-times']['earliest_time'])
latest_time = str(conf['my-times']['latest_time'])
print(earliest_time)
print(latest_time)
But when I'm in this time window and I want to print or use them in an if
-statement, I got the following output:
0:00
1080
How do I print the second time in the code above normally, like how it is in the .yml
file?
CodePudding user response:
The yaml loader is interpreting 17:00 as a time and returns the value as an integer representing the time in minutes. Thus 17:00 will be 1020 and 19:00 will be 1140
EDIT: Code sample to show how one might represent the acquired value in its original form:
import yaml
with open('myconfig.yml') as yml:
conf = yaml.safe_load(yml)
for k in ['earliest_time', 'latest_time']:
e = conf['my-times'][k]
h, m = divmod(e, 60)
print(f'{h:02d}:{m:02d}')
Output:
17:00
19:00
CodePudding user response:
You can change your yaml file:
my-times:
earliest_time: "17:00" #PM
latest_time: "19:00" #PM
This tells YAML that it is a literal string, and inhibits attempts to treat it as a numeric value. Look at this post for more info: https://stackoverflow.com/a/28835540/8961170