Code Monkey home page Code Monkey logo

humantime's Introduction

Human Time

Status: stable

Documentation | Github | Crate

Features:

  • Parses durations in free form like 15days 2min 2s
  • Formats durations in similar form 2years 2min 12us
  • Parses and formats timestamp in rfc3339 format: 2018-01-01T12:53:00Z
  • Parses timestamps in a weaker format: 2018-01-01 12:53:00

Timestamp parsing/formatting is super-fast because format is basically fixed.

Here are some micro-benchmarks:

test result: ok. 0 passed; 0 failed; 26 ignored; 0 measured; 0 filtered out

     Running target/release/deps/datetime_format-8facb4ac832d9770

running 2 tests
test rfc3339_chrono            ... bench:         737 ns/iter (+/- 37)
test rfc3339_humantime_seconds ... bench:          73 ns/iter (+/- 2)

test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured; 0 filtered out

     Running target/release/deps/datetime_parse-342628f877d7867c

running 6 tests
test datetime_utc_parse_millis  ... bench:         228 ns/iter (+/- 11)
test datetime_utc_parse_nanos   ... bench:         236 ns/iter (+/- 10)
test datetime_utc_parse_seconds ... bench:         204 ns/iter (+/- 18)
test rfc3339_humantime_millis   ... bench:          28 ns/iter (+/- 1)
test rfc3339_humantime_nanos    ... bench:          36 ns/iter (+/- 2)
test rfc3339_humantime_seconds  ... bench:          24 ns/iter (+/- 1)

test result: ok. 0 passed; 0 failed; 0 ignored; 6 measured; 0 filtered out

See humantime-serde for serde integration (previous crate serde-humantime looks unmaintained).

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

humantime's People

Contributors

bond-009 avatar dividinglimits avatar gh0st42 avatar juici avatar koushiro avatar neolegends avatar oherrala avatar tailhook avatar veetaha avatar vrmiguel avatar xoac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

humantime's Issues

Only UTC timezone for ISO 8601

Hello!
I use humantime-serde to work with json, it works fine!

But I was a bit confused with it behavior with ISO 8601 formatted strings without timezone.
Strings like that: "2022-07-12T12:01:48" are interpreted like UTC time zone.
After that I checked the documentation for rfc3339.
There are the same additional notices for all rfc3339 functions: "The value is always UTC and ignores system timezone".

Maybe this crucial information could be noticed in 'Features:' for rfc3339 ?
It could save time for many careless(like me) developers

I greatly would appreciate your response and time taken to write it. =)

Different formats?

Are there any plans to support different output formats? I know that some different formats were discussed in #1, but I don't think anything happened like that. I would like to be able to specify a space before the units.

Currently: 5h 3m 2s
Desired: 5 h 3 m 2 s

It would be great to specify the values like in strftime, so like:

format_duration(duration, "%H hours and %M minutes and I don't care about seconds!");

You could really do whatever you want. Are there any plans for anything like this?

approximate time formatting?

When I saw the title "humantime", I thought I'd have something that I could use to give a friendly output of how long my program has run (i.e. when it's been running for 36 days, I don't care about picoseconds).

Would adding that as a feature be of interest?

Windows seems to lack nano Precision

This seems like a standard library / windows target feature ?

https://github.com/pinkforest/humantime/actions/runs/5357555855/jobs/9718572323#step:4:96

I had to work/around it in multi-platform CI:

I sent a PR to add CI which replicates the feature which the above action is from:

I'll send a PR to gate the test

       // TODO: precision bug / feature in Windows side !?                                                                                                           
       // https://github.com/pinkforest/humantime/actions/runs/5357555855/jobs/9718572323#step:4:96                                                             
        #[cfg(not(target_os = "windows"))]
        assert_eq!(
            format_rfc3339_nanos(UNIX_EPOCH +
                Duration::new(1_518_563_312, 789_456_123)).to_string(),
            "2018-02-13T23:08:32.789456123Z");
        #[cfg(target_os = "windows")]
        assert_eq!(
            format_rfc3339_nanos(UNIX_EPOCH +
                Duration::new(1_518_563_312, 789_456_123)).to_string(),
            "2018-02-13T23:08:32.789456100Z");

Please impl Default for humantime::Duration

std::time::Duration implements Default and uses a zero duration for default().

Please add this possibility to humantime! I use the Duration in configuration options. However, it becomes quite verbose to derive things like Default or serde::Deserialize with a #[serde(default)].

I can also make a PR if wished.

Extend format_duration with rounding to milliseconds, seconds, minutes, hours, days, month and years

Sometimes displaying durations in their full precision is not needed and counter productive. Especially in logs where the quantity of a duration is in a seconds/minute/hour range the formatting of ms, us and ns might want to be omitted.

The boilerplate workaround I did some times is (beside creating a trait and blah blah...) is to do something like

format_duration(Duration::from_secs(duration.as_secs());

to get rid of the subsec part.

A possible extension could look like

/// Formats duration into a human-readable string with second precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use humantime::format_duration;
///
/// let val = Duration::new(9420, 1_000_000);
/// assert_eq!(format_duration_secs(val).to_string(), "2h 37m");
/// ```
pub fn format_duration_secs(val: Duration) -> FormattedDuration { ... }

/// ...
pub fn format_duration_min(val: Duration) -> FormattedDuration { ... }

/// ...
pub fn format_duration_hour(val: Duration) -> FormattedDuration { ... }
...

If applicable I happily file a PR.

thanks

Maintenance Status

Hi @tailhook just wondering what is the maintenance status around humantime ?

It's using rather old version of time ^0.1 ? the current 0.1 is 0.1.42 over 3 years ago - dev has moved to 0.3

Appreciate they are just development deps but anyways ๐Ÿคทโ€โ™€๏ธ

src/date.rs: let s = time::at_utc(time::Timespec { sec: sec as i64, nsec: 0 })
And rand would be best idea to bump to 0.8 .. 0.6 is using oudated deps

src/duration.rs:    use rand::Rng;
src/duration.rs:    fn random_second() {
src/duration.rs:            let sec = rand::thread_rng().gen_range(0, 253_370_764_800);
src/duration.rs:    fn random_any() {
src/duration.rs:            let sec = rand::thread_rng().gen_range(0, 253_370_764_800);
src/duration.rs:            let nanos = rand::thread_rng().gen_range(0, 1_000_000_000);
src/date.rs:    use rand::Rng;
src/date.rs:    fn random_past() {
src/date.rs:            let sec = rand::thread_rng().gen_range(0, upper);
src/date.rs:    fn random_wide_range() {
src/date.rs:            let sec = rand::thread_rng().gen_range(0, max::SECONDS);

Could we bump time to ^0.3 and rand to ^0.8 - I sent a PR:
#32

Improve parse_duration error when missing units

fn main() {
    println!("{}", humantime::parse_duration("100").unwrap_err());
}
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/testing`
unknown unit at 3-3

The error message says "unknown unit at 3-3" which is not particularly understandable if someone isn't already familiar with humantime. It would be better to have the message recognize the specific common case of digits-only and produce a targeted message that includes the caller's number with some illustrative unit suffixes. Maybe: "needs time units, for example 100ms or 100sec" where the number is always the same one the caller passed.

A better error message would be a big improvement when using humantime in a cli, such as with structopt:

#[derive(StructOpt)]
struct Args {
    ...

    /// Timeout for operation O, e.g. 30sec or 2min
    #[structopt(
        long,
        default_value = "5min",
        parse(try_from_str = "humantime::parse_duration")
    )]
    timeout: Duration,
}
$ ./cli --timeout 100
error: Invalid value for '--timeout <timeout>': unknown unit at 3-3

(Partial) Support for no_std

It would be really nice to be able to use this crate or a subset of it in no_std environments.

Most parts currently imported from std:: have equivalents in core::.
After a quick look, the biggest show stopper is the missing of an Error alternative in no_std environments.

Maybe parts of the crate can be left out but it would be really cool to use humantime in IoT projects.

regex for supported inputs

is there a regex that can be used to check whether the provided string is in a format that can be parsed by this library?

for the purposes of using in a jsonschema

Serde support as a cargo feature

Currently, 2 dependencies are needed for using humantime and also de/serializing types:

humantime = "2.1.0"
humantime-serde = "1.1.1"

Wouldn't it be nice to unite these dependencies behind a feature gate? e.g.

humantime = { version = "2.1.0", features = ["serde"] }

This could be possibly done by adding a serde feature and exposing the humantime-serde crate if this feature is enabled. I'd be happy to submit a PR.

Or is it better to have these dependencies separated?

Any thoughts? @tailhook @jean-airoldie

suggestion: support a const initializer

Since Durations can be created with const fns, it would be nice if humantime::Duration could also.

It would be ideal if From and Into could be const. Since I don't believe that's possible, perhaps the following added to humantime::Duration:

    pub const fn new(std: StdDuration) -> Self {
        Self(std)
    }

Alternatively, would it be feasible to make the inner StdDuration public (i.e. pub struct Duration(pub StdDuration))? Then the const initializer wouldn't be strictly necessary, and it would give other convenient ways to access the inner duration (i.e. without using the Into or Deref+Copy impls).

I was excited to discover this crate today, because it is a pretty good fit for clap derive-style argument parsing, thanks to the addition of FromStr and Display, plus making the command line fields "unit-less" and less error-prone.

Support fractional durations

It would be nice to have 1.5 hour parsed the same way 1 hour 30 min is.

EDIT: the error is currently duration::Error::InvalidCharacter(1).

2 tests are failing on 32bit platforms

failures:
---- date::test::upper_bound stdout ----
	thread 'date::test::upper_bound' panicked at 'overflow when adding duration to time', libcore/option.rs:891:5
---- date::test::random_wide_range stdout ----
	thread 'date::test::random_wide_range' panicked at 'overflow when adding duration to time', libcore/option.rs:891:5
failures:
    date::test::random_wide_range
    date::test::upper_bound
test result: FAILED. 24 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.