-
Rust: chrono, timezone 예제컴퓨터/Rust 2021. 9. 8. 19:55728x90반응형
chrono
예제
이 crate는 rust에서 date를 쉽게 이용할 수 있게 도와준다.
timezone을 쓰기 위해서 파이썬에서처럼 별도의 라이브러리가 필요하다.
Cargo.toml
[dependencies] chrono = "0.4" chrono-tz = "0.5"
src/main.rs
아래 예제는 주말이면 월요일까지 쉬고, 19시 이후에는 다음 날 아침 9시까지 쉬는 예제이다.
Rust에서는 특정 trait까지 사용함을 표시해야 기능을 사용할 수 있는 경우가 많다.
use chrono::{DateTime, Datelike, TimeZone, Timelike, Utc, Weekday}; use chrono_tz::Asia::Seoul; use chrono_tz::Tz; 'main: loop { let seoul_now: DateTime<Tz> = Utc::now().with_timezone(&Seoul); println!("서울 현재 시각: {}", seoul_now); match seoul_now.weekday() { // use chrono::DateLike 필요 Weekday::Sat | Weekday::Sun => { let monday = Seoul .ymd(seoul_now.year(), seoul_now.month(), seoul_now.day()) .and_hms(9, 0, 0) + chrono::Duration::days(7 - seoul_now.weekday().num_days_from_monday() as i64); // use chrono::TimeLink 필요 let difference = (monday - seoul_now).num_seconds(); println!( "Weekend...resting until next KST monday 9am: {} seconds", difference ); sleep(Duration::from_secs(difference as u64)).await; } _ => {} } if seoul_now.hour() >= 19 || seoul_now.hour() <= 8 { let mut next_morning = Seoul .ymd(seoul_now.year(), seoul_now.month(), seoul_now.day()) .and_hms(9, 30, 0); if seoul_now.hour() >= 19 { next_morning = next_morning + chrono::Duration::days(1); } let difference = (next_morning - seoul_now).num_seconds(); println!( "Night time...resting until next KST 9am: {} seconds", difference ); sleep(Duration::from_secs(difference as u64)).await; continue 'main; } // some actions }
참고
여러 가지 타입이 있는데 아래를 참고하면 될 것 같다.
예제:
- "2020-04-12" => Date = NaiveDate
- "22:10" => Time = NaiveTime
- "2020-04-12 22:10:57" => Date + Time = NaiveDateTime
- "2020-04-12 22:10:57+02:00" => Date + Time + TimeZone = DateTime<Tz>
The ParseError(NotEnough) shows up when there is not enough information to fill out the whole object. For example the date, time or timezone is missing.
When the formats doesn't match the string you get a ParseError(TooShort) or ParseError(Invalid) error.Specification for string format e.g. "%Y-%m-%d %H:%M:%S": https://docs.rs/chrono/latest/chrono/format/strftime/index.html
RFC2822 = Date + Time + TimeZone
To convert a RFC2822 string use the parse_from_rfc2822(..) function.
let date_str = "Tue, 1 Jul 2003 10:52:37 +0200"; let datetime = DateTime::parse_from_rfc2822(date_str).unwrap();
RFC3339 = Date + Time + TimeZone
To convert a RFC3339 or ISO 8601 string use the parse_from_rfc3339(..) function.
let date_str = "2020-04-12T22:10:57+02:00"; // convert the string into DateTime<FixedOffset> let datetime = DateTime::parse_from_rfc3339(date_str).unwrap(); // convert the string into DateTime<Utc> or other timezone let datetime_utc = datetime.with_timezone(&Utc);
Date + Time + Timezone (other or non-standard)
To convert other DateTime strings use the parse_from_str(..) function.
let date_str = "2020-04-12 22:10:57 +02:00"; let datetime = DateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S %z").unwrap();
Date + Time
When you do not have a TimeZone you need to use NaiveDateTime. This object does not store a timezone:
let date_str = "2020-04-12 22:10:57"; let naive_datetime = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").unwrap();
Date
If we where parsing a date (with no time) we can store it in a NaiveDate. This object does not store time or a timezone:
let date_str = "2020-04-12"; let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
Time
If we where parsing a time (with no date) we can store it in a NaiveTime. This object does not store a date or a timezone:
let time_str = "22:10:57"; let naive_time = NaiveTime::parse_from_str(time_str, "%H:%M:%S").unwrap();
Add Date, Time and/or Timezone
If we have some string and want to add more information we can change the type. But you have to provide this information yourself.
let date_str = "2020-04-12"; // From string to a NaiveDate let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap(); // Add some default time to convert it into a NaiveDateTime let naive_datetime: NaiveDateTime = naive_date.and_hms(0,0,0); // Add a timezone to the object to convert it into a DateTime<UTC> let datetime_utc = DateTime::<Utc>::from_utc(naive_datetime, Utc);
위 예제 온라인 실행: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d2b83b3980a5f8fb2e798271766b4541
728x90'컴퓨터 > Rust' 카테고리의 다른 글
Floating Parsing: Eisel-Lemire algorithm (0) 2021.09.14 Rust: Cross compile to linux on windows (0) 2021.08.30 Rust: actix + MongoDB (0) 2021.08.28