miscellaneous¶
Date and Time¶
example
yml
# YAML allows you to represent dates in a standard format, typically following the ISO 8601 standard (YYYY-MM-DD).
birth_date: 1990-12-31
# Times can also be represented using the ISO 8601 standard (HH:MM:SS).
meeting_time: 14:30:00
# YAML supports full timestamps, combining date and time.
event_timestamp: 2023-04-06T14:30:00Z
# Including a time zone in the timestamp ensures clarity across different regions.
local_timestamp: 2023-04-06T14:30:00+05:30
# Specify a range of dates or times using a custom format.
date_range: "2023-04-01 to 2023-04-07"
time_range: "14:30:00 to 15:30:00"
Custom Data Types 🛠️¶
You can define custom data types using tags.
yml
!color
name: Blue
code: "#0000FF"
- The
!color
tag is a custom type indicating that this mapping represents a color with a name and code.
Python Program to Read a YAML File 🐍📄¶
cmd
pip install pyyaml
Create a YAML file (example.yaml)
yml
# example.yaml
name: chaitu-ycr
age: 30
address:
street: 123 Main St
city: chennai
zip: 12345
hobbies:
- Reading
- Hiking
- Coding
Python Script to read the YAML file
import yaml
# Function to read a YAML file
def read_yaml(file_path):
with open(file_path, 'r') as file:
data = yaml.safe_load(file)
return data
# Path to the YAML file
yaml_file = 'example.yaml'
# Reading the YAML file
data = read_yaml(yaml_file)
# Printing the data
print(data)
python output
{
'name': 'chaitu-ycr',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'chennai',
'zip': 12345
},
'hobbies': ['Reading', 'Hiking', 'Coding']
}
Python Program to Create a YAML File 🐍📄¶
Python Script to create and write to a YAML file
import yaml
# Sample data to be written to the YAML file
data = {
'name': 'chaitu-ycr',
'age': 30,
'address': {
'street': '123 Main St',
'city': 'chennai',
'zip': 12345
},
'hobbies': ['Reading', 'Hiking', 'Coding']
}
# Function to write data to a YAML file
def write_yaml(file_path, data):
with open(file_path, 'w') as file:
yaml.dump(data, file, default_flow_style=False)
# Path to the YAML file
yaml_file = 'output.yaml'
# Writing the data to the YAML file
write_yaml(yaml_file, data)
print(f"Data written to {yaml_file}")
The content of the output.yaml file will be
yml
name: chaitu-ycr
age: 30
address:
street: 123 Main St
city: chennai
zip: 12345
hobbies:
- Reading
- Hiking
- Coding