我希望以这种格式获取时间戳:MMDDYYYYHHMMSS
对于 avro 模式格式,我可以使用:
{
"logicalType": "timestamp-millis"
"type": "long",
"date-format": "MMDDYYYYHHMMSS"
}
还是有更好的方法来做到这一点?
根据您的标签,您似乎正在使用 fastavro。默认情况下,fastavro 会将 a 解码timestamp-millis
为datetime
对象。给定一个datetime
对象,您可以使用该strftime
函数将其转换为您想要的格式。
相反,如果您希望它自动解码为具有您指定格式的字符串,则需要修补当前解码器以执行您想要的操作。这是一个可以执行此操作的示例脚本:
import io
from datetime import datetime
import fastavro
from fastavro import writer, reader
original_decoder = fastavro.read.LOGICAL_READERS["long-timestamp-millis"]
def decode_as_custom_string(data, *args):
dt = original_decoder(data, *args)
return dt.strftime("%m%d%Y%H%M%S")
fastavro.read.LOGICAL_READERS["long-timestamp-millis"] = decode_as_custom_string
writer_schema = fastavro.parse_schema({
"type": "record",
"name": "root",
"fields": [
{
"name": "some_date",
"type": [
"null",
{
"type": "long",
"logicalType": "timestamp-millis",
},
],
},
]
})
records = [
{"some_date": datetime.now()}
]
bio = io.BytesIO()
writer(bio, writer_schema, records)
bio.seek(0)
for record in reader(bio):
print(record)