Skip to content

Instantly share code, notes, and snippets.

@mapi68
Last active May 6, 2024 10:28
Show Gist options
  • Save mapi68/60e0eac8d541414933f244727da8fbd0 to your computer and use it in GitHub Desktop.
Save mapi68/60e0eac8d541414933f244727da8fbd0 to your computer and use it in GitHub Desktop.
This Python script provides functions for converting between Unix time and human-readable date-time format.
import arrow
def show_current_time():
current_time = arrow.utcnow()
formatted_current_time = current_time.format("YYYY-MM-DD HH:mm:ss")
unix_time = int(current_time.timestamp())
print(f"Current Time: {formatted_current_time}")
print(f"Unix Time: {unix_time}")
def convert_unix_time(unix_time):
if (
unix_time > 1e10
): # If the number is greater than 10 billion, assume it's in milliseconds
unix_time_seconds = unix_time / 1000
else:
unix_time_seconds = unix_time
timestamp = arrow.get(unix_time_seconds).to("utc")
formatted_time = timestamp.format("YYYY-MM-DD HH:mm:ss")
return formatted_time
def convert_to_unix_time(input_value):
try:
datetime_object = arrow.get(input_value, "YYYY-MM-DD HH:mm:ss").to("utc")
min_timestamp = arrow.get("1970-01-01 00:00:00").timestamp()
max_timestamp = 1e18 # You can set an arbitrary maximum value
unix_time = int(
max(min(datetime_object.timestamp(), max_timestamp), min_timestamp)
)
return unix_time
except arrow.parser.ParserError:
raise ValueError(
'Error: Invalid date and time format. Use the format "YYYY-MM-DD HH:mm:ss".'
)
def automatic_conversion(user_input_value):
try:
if user_input_value.isdigit():
# If the input is a number, perform conversion from Unix time to date and time
unix_time = int(user_input_value)
converted_time = convert_unix_time(unix_time)
print(f"Unix time entered: {unix_time}")
print(f"Converted time: {converted_time}")
else:
# If the input is not a number, try conversion from date and time to Unix time
unix_time = convert_to_unix_time(user_input_value)
print(f"Date and time entered: {user_input_value}")
print(f"Converted Unix time: {unix_time}")
except ValueError as ve:
print(f"Error: {str(ve)}")
# Display current time and Unix time
show_current_time()
# Ask the user to enter Unix time or date and time
user_input = input("Enter Unix time or date and time: ")
automatic_conversion(user_input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment