import time t = time.ctime()
For me at the moment, t
is 'Sat Apr 21 11:58:02 2012'
. I have more data like this.
My question is:
t
to datetime
in Python? Are there any modules to to it?I tried to make a time dict
and then convert t
, but feel like that’s not the best way to do it in Python.
Details:
ctime
list (like ['Sat Apr 21 11:56:48 2012', 'Sat Apr 21 11:56:48 2012']
). datetime
, then store that in a db
with timestamp
.You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.
Python time method ctime() converts a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Python datetime: datetime. now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today().
You should use strptime
: this function parses a string representing a time according to a format. The return value is a struct_time.
The format parameter defaults to %a %b %d %H:%M:%S %Y
which matches the formatting returned by ctime().
So in your case just try the following line, since the default format is the one from ctime:
import datetime import time datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
Returns: datetime.datetime(2012, 4, 21, 4, 22, 00)
Try datetime.strptime()
.
See: http://docs.python.org/library/datetime.html#datetime.datetime.strptime
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