Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-04-26
Convert Datetime to Unix Timestamp in Python

How to convert Datetime to Unix timestamp in Python

🎈 🎈 🎈
+1

    import datetime

    # Example date 
    date_str = '2027-04-30 18:32:02'
    
    # Convert the string to a datetime object
    date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    
    # Convert the datetime object to a Unix timestamp
    timestamp = int(date_time.timestamp())
    
    print("Unix Timestamp:", timestamp)
        

Output:
Unix Timestamp: 1809109922
Example only. There may be multiple ways to perform this operation.

Code Explanation

This Python code converts a date string ('2023-08-24 00:00:00') into a Unix timestamp. It first imports the datetime module, then uses the strptime() method to parse the string into a datetime object, specifying the format 'YYYY-MM-DD HH:MM:SS' to ensure correct interpretation. Once converted, the timestamp() method is called on the datetime object to obtain the corresponding Unix timestamp (the number of seconds since January 1, 1970).
Finally, the Unix timestamp is printed to the console, displaying it as an integer.


Other useful Python date functions

Function Description Example
time.time() Returns the current time in seconds since the Unix epoch (January 1, 1970). The result is a floating-point number representing seconds. time.time() returns 1623433347.2537498
time.sleep(seconds) Suspends (delays) execution for a specified number of seconds. time.sleep(5) pauses for 5 seconds
time.ctime([secs]) Converts a time expressed in seconds since the epoch to a string representing local time. time.ctime(1623433347) returns Tue Jun 11 17:15:47 2021
time.strftime(format[, t]) Formats a time tuple into a string based on a specified format. time.strftime('%Y-%m-%d %H:%M:%S') returns 2021-06-11 17:15:47
time.gmtime([secs]) Converts seconds since the epoch to a struct_time in UTC. time.gmtime(1623433347) returns time.struct_time(tm_year=2021, tm_mon=6, tm_mday=11, ...)
time.localtime([secs]) Converts seconds since the epoch to a struct_time in local time. time.localtime(1623433347) returns time.struct_time(tm_year=2021, tm_mon=6, tm_mday=11, ...)
time.mktime(t) Converts a struct_time representing local time to seconds since the epoch. time.mktime(time.localtime()) returns 1623433347.0
time.monotonic() Returns the value (in fractional seconds) of a monotonic clock, which cannot go backward. time.monotonic() returns 3729.8494781
time.perf_counter() Returns the value (in fractional seconds) of a performance counter, useful for benchmarking. time.perf_counter() returns 27.494923
time.process_time() Returns the CPU time (in seconds) for the current process. time.process_time() returns 0.115742
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-04-26
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder