Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert `ctime` to `datetime` in Python?

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:

  • How to convert 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:

  • I have a ctime list (like ['Sat Apr 21 11:56:48 2012', 'Sat Apr 21 11:56:48 2012']).
  • I want to convert the contents to datetime, then store that in a db with timestamp.
like image 958
flreey Avatar asked Apr 21 '12 04:04

flreey


People also ask

How do I convert a time stamp to a date in python?

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.

How do you use Ctime in Python?

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

Can we convert string to datetime in Python?

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.

What is datetime datetime now () in Python?

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


2 Answers

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)

like image 66
Charles Menguy Avatar answered Sep 30 '22 06:09

Charles Menguy


Try datetime.strptime().

See: http://docs.python.org/library/datetime.html#datetime.datetime.strptime

like image 27
zognortz Avatar answered Sep 30 '22 06:09

zognortz