Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Convert Unix Timestamp to Datetime in OCaml

How to convert Unix timestamp to Datetime in OCaml

🎈 🎈 🎈
+1

    open Unix

    (* Convert Unix timestamp to Date *)
    let unix_timestamp = 1733127551 (* Unix timestamp as float *)
    let tm = Unix.gmtime unix_timestamp
    
    let () =
        Printf.printf "Converted Date: %04d-%02d-%02d %02d:%02d:%02d\n"
        (tm.tm_year + 1900) (tm.tm_mon + 1) tm.tm_mday
        tm.tm_hour tm.tm_min tm.tm_sec            
        

Output:
Converted Date: 2024-12-02 08:19:11
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Ocaml snippet, the Unix timestamp 1733127551 is converted to a human-readable date using the Unix.gmtime function, which returns a tm record. This record contains fields such as tm_year, tm_mon, tm_mday, tm_hour, tm_min, and tm_sec. These values are printed in the format yyyy-MM-dd HH:mm:ss using Printf.printf.
The tm_year field contains the number of years since 1900, so 1900 is added to it, and tm_mon is zero-based, so 1 is added.
In this example the result is 2024-12-02 08:19:11.



Other useful OCaml date functions

Function Description Example
Unix.time() Returns the current Unix timestamp (seconds since 1970-01-01). Unix.time() returns 1693227296.0
Unix.gmtime() Converts a Unix timestamp to a tm structure in UTC. Unix.gmtime(1589530245.0) returns the corresponding date and time in UTC.
Unix.localtime() Converts a Unix timestamp to a tm structure in the local time zone. Unix.localtime(1589530245.0) returns the date and time in the local time zone.
Unix.mktime() Converts a tm structure to a Unix timestamp. Unix.mktime(tm) converts a tm structure to a Unix timestamp.
Unix.strftime() Formats a tm structure as a string according to the specified format. Unix.strftime "%Y-%m-%d" tm returns "2020-05-15"
Unix.strptime() Parses a date string into a tm structure using a format string. Unix.strptime "%Y-%m-%d" "2020-05-15" parses the string into a tm structure.
Unix.sleep() Suspends the execution of the program for the specified number of seconds. Unix.sleep(5) suspends the program for 5 seconds.
Unix.gettimeofday() Returns the current time as a floating-point number of seconds since the epoch, including fractional seconds. Unix.gettimeofday() returns 1693227296.123
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder