I am trying to convert a datestamp of now into Unix TimeStamp, however the code below seems to be hit but then just jumps to the end of my app, as in seems to not like the time.mktime part.
from datetime import datetime
import time
now = datetime.now()
toDayDate = now.replace(hour=0, minute=0, second=0, microsecond=0)
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
print(newDate)
In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).
We can convert a datetime object into a timestamp using the timestamp() method. If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the tzinfo parameter of the datetime object and then call the timestamp() method.
However, Windows and Unix-like systems such as Linux and macOS (10 and above) all use Unix's definition of epoch (i.e., 1970-01-01 00:00:00 UTC), so Python's timestamp functions are effectively Unix timestamp functions when they're called on these operating systems.
Change
newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())
to
newDate = time.mktime(datetime.timetuple())
as an example I did:
from datetime import datetime
from time import mktime
t = datetime.now()
unix_secs = mktime(t.timetuple())
and got unix_secs = 1488214742.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With