Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to unix timestamp Python

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)
like image 755
user3182518 Avatar asked Feb 27 '17 16:02

user3182518


People also ask

How do you create a Unix timestamp in Python?

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).

How do I convert a timestamp in Python?

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.

What is Unix timestamp in Python?

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.


1 Answers

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

like image 113
Dillanm Avatar answered Sep 30 '22 01:09

Dillanm