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

Question:

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.
Asked By: flreey

||

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)

Answered By: Charles Menguy

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("ntToday's date: {} Type: {}n".format(a, type(a)))
print("ntToday'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("ntToday'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("ntToday'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("ntToday'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("ntToday'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("ntToday'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("ntToday'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

Answered By: JayRizzo

Just use %c:

datetime.datetime.strptime(time.ctime(), "%c")
Answered By: CiroG
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.