use chrono::{DateTime, Utc, TimeZone};
use humantime::parse_duration;
use serde_json::Value;
use std::time::SystemTime;
pub fn parse_time_string(time_str: &str) -> Result<DateTime<Utc>, String> {
if time_str.to_lowercase() == "now" {
return Ok(Utc::now());
}
let clean_str = time_str.strip_suffix(" ago").unwrap_or(time_str);
if let Ok(duration) = parse_duration(clean_str) {
let now = SystemTime::now();
let target_time = now - duration;
return Ok(target_time.into());
}
if let Ok(datetime) = DateTime::parse_from_rfc3339(time_str) {
return Ok(datetime.with_timezone(&Utc));
}
Err(format!("Could not parse time string: {}", time_str))
}
pub fn extract_and_parse_timestamp(value: &Value) -> Option<DateTime<Utc>> {
const COMMON_KEYS: [&str; 3] = ["timestamp", "ts", "@timestamp"];
for key in COMMON_KEYS {
if let Some(ts_value) = value.get(key) {
if let Some(ts_str) = ts_value.as_str() {
if let Ok(datetime) = DateTime::parse_from_rfc3339(ts_str) {
return Some(datetime.with_timezone(&Utc));
}
} else if let Some(ts_unix) = ts_value.as_i64() {
if let Some(datetime) = Utc.timestamp_opt(ts_unix, 0).single() {
return Some(datetime);
}
}
}
}
None
}