36
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.
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
flreey
  • 405
  • 1
  • 6
  • 9

4 Answers4

48

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)

JayRizzo
  • 3,234
  • 3
  • 33
  • 49
Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
  • I try that way for hours, but still can't convert 'Sat Apr 21 11:58:02 2012' to datetime correctly. – flreey Apr 21 '12 at 04:22
  • thank you, it's my fault, I put the wrong parameters.datetime.strptime(time.ctime(), '%a %b %d %H:%M:%S %Y') works – flreey Apr 21 '12 at 04:29
  • sorry, i don't know how to close my question? may be you can tell me? – flreey Apr 21 '12 at 04:34
  • @flreey to the left of each answer to your question, there is a little "V" sign that you can click. When your problem is solved, you usually click on it so other can see the good answer, and you gain a couple reputation points, and the answer that is accepted as well. It is just under the number of votes to the left of each answer. You should do it on all your questions. – Charles Menguy Apr 21 '12 at 04:37
5

Just use %c:

datetime.datetime.strptime(time.ctime(), "%c")
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
CiroG
  • 59
  • 1
  • 1
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – n1colas.m Jun 19 '20 at 21:30
3

Try datetime.strptime().

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

Zearin
  • 1,474
  • 2
  • 17
  • 36
zognortz
  • 101
  • 4
  • i've try strptime, but it can't work correctly. So i ask question here – flreey Apr 21 '12 at 04:14
  • I mean i can't convert 'Sat Apr 21 11:58:02 2012' to datetime using that method. – flreey Apr 21 '12 at 04:23
  • Perhaps try showing us your code where you're attempting to use datetime.strptime(), and show us the incorrect output that your code gives. – zognortz Apr 21 '12 at 04:27
  • thanks, I using the methond incorrect. datetime.strptime(time.ctime(), '%a %b %d %H:%M:%S %Y') work – flreey Apr 21 '12 at 04:29
-2

Convert the 'time.ctime()' to datetime

time.ctime() by default returns a string. you can just format this as shown in the other answers


import datetime
import time
from time import strptime

# Print the ctime -- Result type is already a string
a = time.ctime()
print("\n\tToday's date: {} Type: {}\n".format(a, type(a)))
print("\n\tToday's date: {} Type: {}\n".format(time.ctime(), type(time.ctime())))

# just convert that to a datetime 
c = datetime.datetime.strptime(a, "%a %b %d %H:%M:%S %Y")
print("\n\tToday's date: {} Type: {}\n".format(c, type(c)))

# %a - abbreviated weekday name
# %b - abbreviated month name
# %d - day of the month (01 to 31)
# %H - hour, using a 24-hour clock (00 to 23)
# %M - minute
# %S - second
# %Y - year including the century

d = datetime.datetime.strptime(a, "%c")
print("\n\tToday's date: {} Type: {}\n".format(d, type(d)))

# %c - preferred date and time representation

# Results: 
#     Today's date: Fri Apr 22 15:50:17 2022 Type: <class 'str'>
#     Today's date: Fri Apr 22 15:50:17 2022 Type: <class 'str'>
#     Today's date: 2022-04-22 15:50:17 Type: <class 'datetime.datetime'>
#     Today's date: 2022-04-22 15:50:17 Type: <class 'datetime.datetime'>

Convert the raw class from ctime 'time.struct_time' to date time

Something different, if you want to parse the object and convert it back as follows. Not ideal, just something i found to work different.


import datetime
import time
from time import strptime

# How to Convert the class 'time.struct_time' to date time.
X = strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
print("\n\tToday's date: {} Type: {}\n".format(X, type(X)))

# Create the Date time String from the ctime format:
date_time_str = "{}-{}-{} {}:{}:{}".format(X.tm_year, X.tm_mon, X.tm_mday, X.tm_hour, X.tm_min, X.tm_sec)
print("\n\tToday's date: {} Type: {}\n".format(date_time_str, type(date_time_str)))

# Convert the Date time String from the datetime format:
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
print("\n\tToday's date: {} Type: {}\n".format(date_time_obj, type(date_time_obj)))

# if Needed you can reformat the resulted datetime object:
Y = date_time_obj.strftime("%a %b %d %H:%M:%S %Y")
print("\n\tToday's date: {} Type: {}\n".format(Y, type(Y)))

# Results:
#     Today's date: time.struct_time(tm_year=2022, tm_mon=4, tm_mday=22, tm_hour=15, tm_min=49, tm_sec=25, tm_wday=4, tm_yday=112, tm_isdst=-1) Type: <class 'time.struct_time'>
#     Today's date: 2022-4-22 15:49:25 Type: <class 'str'>
#     Today's date: 2022-04-22 15:49:25 Type: <class 'datetime.datetime'>
#     Today's date: Fri Apr 22 15:49:25 2022 Type: <class 'str'>

# From: https://www.tutorialspoint.com/python/time_strptime.htm
# Directive
# %a - abbreviated weekday name
# %A - full weekday name
# %b - abbreviated month name
# %B - full month name
# %c - preferred date and time representation
# %C - century number (the year divided by 100, range 00 to 99)
# %d - day of the month (01 to 31)
# %D - same as %m/%d/%y
# %e - day of the month (1 to 31)
# %g - like %G, but without the century
# %G - 4-digit year corresponding to the ISO week number (see %V).
# %h - same as %b
# %H - hour, using a 24-hour clock (00 to 23)
# %I - hour, using a 12-hour clock (01 to 12)
# %j - day of the year (001 to 366)
# %m - month (01 to 12)
# %M - minute
# %n - newline character
# %p - either am or pm according to the given time value
# %r - time in a.m. and p.m. notation
# %R - time in 24 hour notation
# %S - second
# %t - tab character
# %T - current time, equal to %H:%M:%S
# %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
# %U - week number of the current year, starting with the first Sunday as the first day of the first week
# %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week
# %W - week number of the current year, starting with the first Monday as the first day of the first week
# %w - day of the week as a decimal, Sunday=0
# %x - preferred date representation without the time
# %X - preferred time representation without the date
# %y - year without a century (range 00 to 99)
# %Y - year including the century
# %Z or %z - time zone or name or abbreviation
# %% - a literal % character

JayRizzo
  • 3,234
  • 3
  • 33
  • 49