How to convert `ctime` to `datetime` in Python? - 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.

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)

Just use %c:
datetime.datetime.strptime(time.ctime(), "%c")

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

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

Related

convert a date into numeric string

How can I convert a date into a numeric date?
For example, I want to convert '06-Jun-2021' to '20210609' and then turn it into a string i can use in a webpage eg. baseball.theater/games/20210609 so that i can automate the process daily.
using datetime i've managed to do :
print (todays_date.year,todays_date.month,todays_date.day,sep="")
which can print the output i need (without the trailing 0's) but i cannot make this into a string which i can use.
obviously i am a COMPLETE newcomer to python, so be gentle please.
You can use datetime.strptime to turn a string into a datetime object, then datetime.strftime to reformat it into a different string.
>>> from datetime import datetime
>>> s = '06-Jun-2021'
>>> dt = datetime.strptime(s, '%d-%b-%Y')
>>> dt.strftime('%Y%m%d')
'20210606
For the specific case of the current day, you can use datetime.today
>>> datetime.today().strftime('%Y%m%d')
'20210609'
To combine this into your final string you can use str.format
>>> 'baseball.theater/games/{}'.format(datetime.today().strftime('%Y%m%d'))
'baseball.theater/games/20210609'
Here, just typecast it to str and use .replace() method
from datetime import date # datetime is a built-in module
today = str(date.today())
string = today.replace("-", "")
print(string)
P.S Just providing an alternate method to strftime
I think you are looking time.strftime()
The function needs time module
import time
then you can either use a variable and display that time in a specific format.
t = time.time()
print(time.strftime('%H%M%S', t) # print the time t in specific format
print(time.strftime('%H%M%S') # print present time in specific format
Here is a list of options from https://www.tutorialspoint.com/
%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

strftime formatting - what am I doing wrong?

I've got a string 3:01 AM - 18 Dec 2017
I've written the following pattern strftime('%-I:%M %p - %-d %b %Y') and I can't seem to get it to work, following this
My notes:
%-I hour 12-hour clock as a decimal (no zero padding)
: separation between hour and minute
%M minute as a zero padded decimal
%p AM/PM
- space-dash-space pattern betwen time and date
%-d date of the month as a decimal (no zero padding)
%b Month abbreviated
%Y Year with century as decimal
df['tweet_date'] = pd.to_datetime(df['tweet_date'], errors='coerce').apply(lambda x: x.strftime('%I:%M %p - %d %b %Y')if not pd.isnull(x) else '')
On another dataframe with a similar column this works:
df2['created_at'] = pd.to_datetime(df2['created_at'], errors='coerce').apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')if not pd.isnull(x) else '')
df2['created_at'] = df2['created_at'].astype('datetime64[s]')`
where values before formatting look like this for example 2017-10-03T15:48:10.000Z
Your format is fine but some os's can't use the negative formatting for zero-padded units. datetime should be able to parse both padded and non-padded instances of those just fine:
from datetime import datetime as dt
z_time = '06:48 PM - 03 Jun 2021'
nz_time = '6:48 PM - 3 Jun 2021'
dt.strptime(z_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
dt.strptime(nz_time, '%I:%M %p - %d %b %Y')
[out:] datetime.datetime(2021, 6, 3, 18, 48)
And since you're getting strings from datetimes, you should look whether your os supports certain formatting rules. Here's one for windows.
from datetime import datetime
str="3:01 AM - 18 Dec 2017"
date=datetime.strptime(str,"%I:%M %p - %d %b %Y")
To turn your string into a time, do this:
>>> import time
>>> s = "3:01 AM - 18 Dec 2017"
>>> time.strptime(s,'%I:%M %p - %d %b %Y')
time.struct_time(tm_year=2017, tm_mon=12, tm_mday=18, tm_hour=3, tm_min=1,
tm_sec=0, tm_wday=0, tm_yday=352, tm_isdst=-1)
No hyphens after %. The are not mentioned in the official Python documentation.
I wanted to figure out how to use strftime in a lambda function or better, using the .dt accessor after the column in my dataframe had been converted to a datetime
I couldn't figure this out so I went for the next fastest method
from datetime import datetime
formatted_dates = []
for item in df.tweet_date:
formatted_dates.append(datetime.strptime(item,"%I:%M %p - %d %b %Y"))
df.tweet_date = formatted_dates

How to convert a string into date-format in python?

I have a string like 23 July 1914 and want to convert it to 23/07/1914 date format.
But my code gives error.
from datetime import datetime
datetime_object = datetime.strptime('1 June 2005','%d %m %Y')
print datetime_object
Your error is in the format you are using to strip your string. You use %m as the format specifier for month, but this expects a 0 padded integer representing the month of the year (e.g. 06 for your example). What you want to use is %B, which expects an month of the year written out fully (e.g. June in your example).
For a full explanation of the datetime format specifiers please consult the documentation, and if you have any other issues please check there first.
Here is what you should be doing:
from datetime import datetime
datetime_object = datetime.strptime('1 June 2005','%d %B %Y')
s = datetime_object.strftime("%d/%m/%y")
print(s)
Output:
>>> 01/06/05
You see your strptime requires two parameters.
strptime(string[, format])
And the string will be converted to a datetime object according to a format you specify.
There are various formats
%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)
The above are some examples. Take a look here for formats
Take a goood look at these two!
%b - abbreviated month name
%B - full month name
It should be in a similar pattern to the string you provide. Confusing take a look at these examples.
>>> datetime.strptime('1 jul 2009','%d %b %Y')
datetime.datetime(2009, 7, 1, 0, 0)
>>> datetime.strptime('1 Jul 2009','%d %b %Y')
datetime.datetime(2009, 7, 1, 0, 0)
>>> datetime.strptime('jul 21 1996','%b %d %Y')
datetime.datetime(1996, 7, 21, 0, 0)
As you can see based on the format the string is turned into a datetime object. Now take a look!
>>> datetime.strptime('1 July 2009','%d %b %Y')
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
datetime.strptime('1 July 2009','%d %b %Y')
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data '1 July 2009' does not match format '%d %b %Y'
Why error because jun or Jun (short form) stands for %b. When you supply a June it gets confused. Now what to do? Changed the format.
>>> datetime.strptime('1 July 2009','%d %B %Y')
datetime.datetime(2009, 7, 1, 0, 0)
Simple now converting the datetime object is simple enough.
>>> s = datetime.strptime('1 July 2009','%d %B %Y')
>>> s.strftime('%d/%m/%Y')
'01/07/2009
Again the %m is the format for displaying it in months (numbers) read more about them.
The placeholder for "Month as locale’s full name." would be %B not %m:
>>> from datetime import datetime
>>> datetime_object = datetime.strptime('1 June 2005','%d %B %Y')
>>> print(datetime_object)
2005-06-01 00:00:00
>>> print(datetime_object.strftime("%d/%m/%Y"))
01/06/2005
This should work:
from datetime import datetime
print(datetime.strptime('1 June 2005', '%d %B %Y').strftime('%d/%m/%Y'))
print(datetime.strptime('23 July 1914', '%d %B %Y').strftime('%d/%m/%Y'))
For more info you can read about strftime-strptime-behavior
%d means "Day of the month as a zero-padded decimal number."
%m means "Month as a zero-padded decimal number."
Neither day or month are supplied what you tell it to expect. What you need it %B for month (only if your locale is en_US), and %-d for day.

Convert string to python date type object with timezone offset using strptime

What is the correct format to convert this string Tue Jan 10 2017 13:00:13 GMT 0800 (Taipei Standard Time) to a python date type object using strptime?
I tried the answer from this question and it is not working for me:
date1 = datetime.strptime(strDate1, '%b %d %Y %I:%M%p')
ValueError: time data 'Tue Jan 10 2017 13:00:13 GMT 0800 (Taipei
Standard Time)' does not match format '%b %d %Y %I:%M%p'
You can format the date without timezone and add it later,
import pytz
date1=datetime.strptime('Tue Jan 10 2017 13:00:13', '%a %b %d %Y %H:%M:%S')
tz=pytz.timezone('Asia/Taipei')
tz.localize(date1)
Nominally you would want to be able to use the %z (lowercase z) to convert the TZ offset, however support for this is sketchy. So you can DIY it:
import datetime as dt
import re
PARSE_TIMESTAMP = re.compile('(.*) ([+-]?\d+) \(.*\)$')
def my_datetime_parse(timestamp):
''' return a naive datetime relative to UTC '''
# find the standard time stamp, and the TZ offset and remove extra end
matches = PARSE_TIMESTAMP.match(timestamp).groups()
# convert the timestamp element
timestamp = dt.datetime.strptime(matches[0], '%a %b %d %Y %H:%M:%S %Z')
# calculate the timezone offset
tz_offset = matches[1]
sign = '+'
if tz_offset[0] in '-+':
sign = tz_offset[0]
tz_offset = tz_offset[1:]
tz_offset += '0' * (4 - len(tz_offset))
minutes = int(tz_offset[0:2]) * 60 + int(tz_offset[2:])
if sign == '-':
minutes = -minutes
# add the timezone offset to our time
timestamp += dt.timedelta(minutes=minutes)
return timestamp
date_string = 'Tue Jan 10 2017 13:00:13 GMT +0800 (Taipei Standard Time)'
print(my_datetime_parse(date_string))
This code produces:
2017-01-10 21:00:13
The code removes the (Taipei Standard Time) since it is redundant with the +0800.

Convert email (rfc 2822) date string to another format (ISO 8601 timestamp) in Python 2.7

I have dates of this format Thu, 18 Feb 2016 15:33:10 +0200
and I want them transformed to 2016-02-12 08:39:09.653475
How can this be achieved with the Python's standard library?
You can do this with the datetime module as follows:
from datetime import datetime
d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S.%f')
Or in python2 you may use instead:
from datetime import datetime
from dateutil.parser import parse
d = 'Thu, 18 Feb 2016 15:33:10 +0200'
datetime.strftime(parse(d), '%Y-%m-%d %H:%M:%S.%f')
or if need to stick with standard library have a look at J.F.Sebastian's comment at How to parse dates with -0400 timezone string in python?
check this link How to print date in a regular format in Python?
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
That will print out something like this:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
To parse the input date format using only stdlib, you could use email.utils package:
>>> from datetime import datetime, timedelta
>>> from email.utils import parsedate_tz, mktime_tz
>>> timestamp = mktime_tz(parsedate_tz('Thu, 18 Feb 2016 15:33:10 +0200'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> str(utc_time)
'2016-02-18 13:33:10'
where str(dt) is equivalent to dt.isoformat(' ').
If you need to support leap seconds; (assuming your platform supports them) use tt = time.gmtime(timestamp) and time.strftime('%Y-%m-%d %H:%M:%S', tt). Note: time.gmtime() may have different limits on different platforms (that are probably less than datetime's limits).

Categories

Resources