Python timestamp to datetime and vice-versa

You’ll mainly use:

from datetime import datetime
datetime.fromtimestamp()
datetime.timestamp()

🕰️ Python — Timestamp ↔ Datetime Assignments


1) Convert Current Datetime to Timestamp

Get the current datetime and convert it to a timestamp. Print the result.


2) Timestamp to Datetime

Convert the timestamp 0 to a datetime and print it. (This is the Unix epoch.)


3) Convert Given Datetime to Timestamp

Create a datetime object for:

2026-01-01 00:00:00

Convert it to a timestamp.


4) Convert Timestamp to Readable

Convert timestamp:

to a human-readable datetime and print.


5) Timestamp from User Date

Ask the user to enter a date/time string:

Convert it to timestamp and print.


6) Datetime from User Timestamp

Ask the user to enter a timestamp (e.g., 1670000000). Convert it to a datetime and print.


7) Compare Timestamps

Get the timestamps for now and for:

Print which is larger.


8) Difference in Seconds

Ask for two timestamps from user and print how many seconds apart they are.


9) Timestamp Before/After Now

Get current timestamp and print whether it is greater than a fixed timestamp (e.g., 1000000000).


10) Days Since Epoch

Convert current timestamp to days since epoch (timestamp // (24*3600)) and print result.


11) Format Converted Datetime

Convert a timestamp to datetime, then print it in:


12) Timestamp from Date Only

Ask for a date string:

Parse it to datetime and print its timestamp.


13) Round Trip Test

Take current datetime → timestamp → back to datetime. Print all three representations.


14) Next Day Timestamp

Take user’s timestamp, add 24 hours (seconds) to it, and convert back to datetime.


15) Previous Hour

Take a timestamp and subtract 3600 seconds; print the resulting datetime.


16) Midnight Timestamp

Convert today’s date at midnight (00:00:00) to a timestamp.


17) UTC Timestamp Conversion

(Optional) Convert a UTC timestamp to a UTC datetime using datetime.utcfromtimestamp().


18) Future Date Timestamp

Ask user for a number of days n, compute the date n days from now, and print its timestamp.


19) Validate Timestamp Input

Ask for a timestamp string. If the input isn’t numeric, catch the error and print “Invalid timestamp”.


20) Sort by Timestamps

Given a list of two datetime objects, convert both to timestamps and print them in ascending order.


🧠 Key Methods You’ll Use


📌 Example Starter Snippet


📝 Helpful Format Tips

To print a timestamp-converted datetime nicely:


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated