Im trying to use strptime to convert a day and time into a DateTime field. That is, convert input like "Friday 3:00 PM" to a datetime field. The event this is for takes place over three consecutive days, so I know that Friday will be a specific day in February, and so on.
My question, is how do I go about doing this? How do I convert, for example, Friday 3:00 PM into 2017-02-24 15:00:00?
What I have right now in my Django project, in views.py is:
new_request.start = time.strptime(form.cleaned_data['start'], '%A %I:%M %p')
Then, I have to print out "Friday 3:00 PM" from the datetime field later, using strftime, which I would assume is the reverse of the above?
Thanks!
You can adapt the example below to achieve what you want exactly:
import time
time.strftime("%Y-%d-%m %H:%M:%S", time.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p'))
# Output: '2017-03-02 15:00:00'
If year and month are fixed to 2017 and February like you mentioned then "Friday 3:00 PM" can be converted as follows:
time.strftime("2017-%d-2 %H:%M:%S", time.strptime('Friday 3 3:00PM', '%A %d %I:%M%p'))
# Output: '2017-03-2 15:00:00'
If you want to get datetime object use the following:
from datetime import datetime
datetime.strptime('Friday 3 February 2017 3:00PM', '%A %d %B %Y %I:%M%p')
# Output: datetime.datetime(2017, 2, 3, 15, 0)
You can use python-dateutil to parse readable time string to datetime object. It's very convenient and easy to use.
Examples from its document page:
>>> from dateutil.relativedelta import *
>>> from dateutil.easter import *
>>> from dateutil.rrule import *
>>> from dateutil.parser import *
>>> from datetime import *
>>> now = parse("Sat Oct 11 17:13:46 UTC 2003")
>>> today = now.date()
>>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year
>>> rdelta = relativedelta(easter(year), today)
>>> print("Today is: %s" % today)
Today is: 2003-10-11
>>> print("Year with next Aug 13th on a Friday is: %s" % year)
Year with next Aug 13th on a Friday is: 2004
>>> print("How far is the Easter of that year: %s" % rdelta)
How far is the Easter of that year: relativedelta(months=+6)
>>> print("And the Easter of that year is: %s" % (today+rdelta))
And the Easter of that year is: 2004-04-11
Related
I need some help on datetime
here is my code:
import datetime
x = int(input()).datetime.datetime()
print(x.strftime("%B, %d, %Y"))
My custom input: 12 25 1990
but I always got an error ValueError: invalid literal for int() with base 10: '12 25 1990'
I just wanted the output to be " December 25, 1990" can anybody help thank you;;
As #Barmar suggested, use datetime.strptime:
import datetime
x = datetime.datetime.strptime(input(), '%m %d %Y')
print(x.strftime("%B %d, %Y"))
output (for input 12 25 1990)
December 25, 1990
You have two options either prepare the datetime object by splitting the input and preparing date, month, etc. as:
import datetime
date_entry = '12 25 1990'
month, day, year = map(int, date_entry.split())
x = datetime.date(year, month, day)
print(x.strftime("%B, %d, %Y"))
Or simply use strptime to create the date from the input format as:
date_entry = '12 25 1990'
res = datetime.datetime.strptime(date_entry, '%m %d %Y')
print(res.strftime("%B, %d, %Y"))
In my python code I get start and end time some thing like:
end = int(time.time())
start = end - 1800
Now start and end variables holds values like 1460420758 and 1460422558.
I am trying to convert it in a meaningful format like :
Mon Apr 11 17:50:25 PDT 2016
But am unable to do so, I tried:
time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime(start))
Gives me
Tue Apr 12 00:25:58 2016
But not only the timezone but the H:M:S are wrong
As date returns me the below information:
$ date
Mon Apr 11 18:06:27 PDT 2016
How to correct it?
This one involves utilizing datetime to great the format you wish with the strftime module.
What's important is that the time information you get 'MUST' be UTC in order to do this. Otherwise, you're doomed D:
I'm using timedelta to 'add' hours to the time. It will also increments the date, too. I still would recommend using the module I shared above to handle time zones.
import time
# import datetime so you could play with time
import datetime
print int(time.time())
date = time.gmtime(1460420758)
# Transform time into datetime
new_date = datetime.datetime(*date[:6])
new_date = new_date + datetime.timedelta(hours=8)
# Utilize datetime's strftime and manipulate it to what you want
print new_date.strftime('%a %b %d %X PDT %Y')
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).
I've got a couple strings from which I want to get the datetime. They are formatted like this:
Thu 2nd May 2013 19:00
I know almost how I can convert this to a datetime, except for that I'm having trouble with the "2nd". I now have the following
>>> datetime.strptime('Thu 02 May 2013 19:00', '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)
which works fine with a zero padded number for the day of the month, but when I try the 2nd, it gives a ValueError:
>>> datetime.strptime('Thu 2nd May 2013 19:00', '%a %d %B %Y %H:%M')
Traceback (most recent call last):
File "<input>", line 1, in <module>
(data_string, format))
ValueError: time data 'Thu 2nd May 2013 19:00' does not match format '%a %d %B %Y %H:%M'
In the list of datetime directives I can't find anything relating to ordered values (1st, 2nd, 3rd etc) for dates. Does anybody know how I can get this to work? All tips are welcome!
Consider using dateutil.parser.parse.
It's a third party library that has a powerful parser which can handle these kinds of things.
from dateutil.parser import parse
s = 'Thu 2nd May 2013 19:00'
d = parse(s)
print(d, type(d))
# 2013-05-02 19:00:00 <class 'datetime.datetime'>
A brief caveat (doesn't really occur in your case): if dateutil can't find an aspect of your date in the string (say you leave out the month) then it will default to the default argument. This defaults to the current date with the time 00:00:00. You can obviously over-write this if necessary with a different datetime object.
The easiest way to install dateutil is probably using pip with the command pip install python-dateutil.
You can preparse the original string to adjust the day to be suitable for your strptime, eg:
from datetime import datetime
import re
s = 'Thu 2nd May 2013 19:00'
amended = re.sub('\d+(st|nd|rd|th)', lambda m: m.group()[:-2].zfill(2), s)
# Thu 02 May 2013 19:00
dt = datetime.strptime(amended, '%a %d %B %Y %H:%M')
# 2013-05-02 19:00:00
It's straightforward to remove the suffix from the date without using regular expressions or an external library.
def remove_date_suffix(s):
parts = s.split()
parts[1] = parts[1].strip("stndrh") # remove 'st', 'nd', 'rd', ...
return " ".join(parts)
Then it's as simple as using strptime as you'd expect:
>>> s = "Thu 2nd May 2013 19:00"
>>> remove_date_suffix(s)
'Thu 2 May 2013 19:00'
>>> datetime.strptime(remove_date_suffix(s), '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)
import re
from datetime import datetime
def proc_date(x):
return re.sub(r"\b([0123]?[0-9])(st|th|nd|rd)\b",r"\1",x)
>>> x='Thu 2nd May 2013 19:00'
>>> proc_date(x)
'Thu 2 May 2013 19:00'
>>> datetime.strptime(proc_date(x), '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)
I've got a bunch of date strings in this form: -
30th November 2009
31st March 2010
30th September 2010
I want them like this: -
YYYYMMDD
Currently I'm doing this: -
parsed_date = "30th November 2009"
part = parsed_date.split(' ')
daymonth = part[0].strip(string.ascii_letters)
mytime = daymonth+" "+part[1]+" "+part[2]
time_format = "%d %B %Y"
cdate = time.strptime(mytime, time_format)
newdate = str(cdate[0])+str(cdate[1])+str(cdate[2])
It works, but I'm sure there is a better way...
Try dateutil:
from dateutil import parser
dates = ['30th November 2009', '31st March 2010', '30th September 2010']
for date in dates:
print parser.parse(date).strftime('%Y%m%d')
output:
20091130
20100331
20100930
or if you want to do it using standard datetime module:
from datetime import datetime
dates = ['30th November 2009', '31st March 2010', '30th September 2010']
for date in dates:
part = date.split()
print datetime.strptime('%s %s %s' % (part[0][:-2]), part[1], part[2]), '%d %B %Y').strftime('%Y%m%d')
You can almost do this with a combination of strptime and strptime from the datetime module.
The problem we have is that the built-in formats support dates like 30 November 2010 but not 30th November 2010. So in the example below I've used a regular expression substitution to strip out the problem characters. (The regular expression uses a look-behind to see if "st", "nd", "rd" or "th" is preceeded by a digit, and if so replaces it with the empty string, thus removing it from the string.)
>>> import re
>>> from datetime import datetime
>>> mydate = "30th November 2009"
>>> mydate = re.sub("(?<=\d)(st|nd|rd|th)","",mydate)
>>> mydate
'30 November 2009'
>>> mydatetime = datetime.strptime(mydate,"%d %B %Y")
>>> mydatetime
datetime.datetime(2009, 11, 30, 0, 0)
>>> mydatetime.strftime("%Y%M%d")
'20090030'
In python 3.7, you can use isoformat()
>>> from datetime import datetime
>>> datetime.today().date().isoformat().replace("-", "")
'20190220'