New API functions: date and time (breaks backward compatibility)

Datetime frontmatter fields are automatically detected
This commit is contained in:
faildev_mode 2023-06-27 14:17:44 +02:00
parent 22a62f7453
commit 08aaa2f6fa
No known key found for this signature in database
GPG Key ID: 70845C70C0F5E205
2 changed files with 26 additions and 17 deletions

View File

@ -1,5 +1,6 @@
import os
from item import Item # from itself
import datetime
class Content:
"""This class contains some functions useful for evaluation of Python code in content files"""
@ -39,3 +40,17 @@ class Content:
for entry in os.scandir('content/'+dir):
item = Item(os.path.relpath(entry.path, start='content'))
if item.title: yield item
def date(src) -> str:
"""Returns date string from datetime or date object"""
if type(src) != datetime.time:
return src.strftime('%Y-%m-%d')
return ''
def time(src) -> str:
"""Returns time string from datetime or time object"""
if type(src) != datetime.date:
return src.strftime('%H:%M')
return ''

View File

@ -1,7 +1,7 @@
import frontmatter # from package python-frontmatter
import datetime
from files import read_this # from itself
from config import config
from config import config # from itself
from attrdict import AttrDict # from itself
class Item(AttrDict):
@ -12,11 +12,9 @@ class Item(AttrDict):
tags = []
description = None
source = None
date = None
time = None
author = None
def __init__(self, path):
def __init__(self, path: str):
# initialize parent
super().__init__()
@ -31,17 +29,13 @@ class Item(AttrDict):
if field not in frontmatter_data:
frontmatter_data[field] = config['defaults'][field]
# share frontmatter fields
for field in frontmatter_data:
if field == 'created':
# frontmatter produces date objects if created field is in format yyyy-mm-dd
# if it contains time as in ISO 8601, we want to convert it to datetime
# https://en.wikipedia.org/wiki/ISO_8601
if type(frontmatter_data['created']) == str:
frontmatter_data['created'] = datetime.datetime.fromisoformat(
frontmatter_data['created'])
self.date = str(frontmatter_data['created'].date())
self.time = str(frontmatter_data['created'].time())
else:
self.date = str(frontmatter_data['created'])
else:
self[field] = frontmatter_data[field]
self[field] = frontmatter_data[field]
# convert ISO datetime strings into datetime objects
if type(self[field]) == str:
try: self[field] = datetime.date.fromisoformat(self[field])
except ValueError:
try: self[field] = datetime.datetime.fromisoformat(self[field])
except ValueError: pass