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"))
Related
I'm reading (actually scraping) an RSS feed of NOAA buoy data. One of the data is the date and time the data was collected at the buoy. So the string I am extrapolating is in this format: January 10, 2023 9:48 am
But if the time is on the hour, say 'January 10, 2023 10:00 am', the feed produces an extra variable that throws my output off.
Thus, my code would check to see if the feed is on the hour and change the variables, like so:
air_temp = rows[7]
water_temp = rows[8]
if [time minutes = '00']:
air_temp = rows[7]
water_temp = rows[8]
I'm assuming I would need to change the time string to datetime in order to write the If statement? (Otherwise, I'm happy with the string format as is for my output.)
to check if the time is on the hour, you could do this to convert it to a datetime, then check if the minutes are zero:
from datetime import datetime as dt
date = 'January 10, 2023 10:00 am'
datetime = dt.strptime(s, '%B %d, %Y %H:%M %p')
minute = datetime.minute
if minute == 0:
do whatever
you could also do this which requires less thinking about the date format :)
import pandas as pd
pd.to_datetime(date)
You can use datetime for the same and convert your input time format to python's datetime data type.
import datetime
input_str = 'January 10, 2023 9:48 am'
input_time_format = '%B %d, %Y %I:%M %p'
datetime_str = datetime.datetime.strptime(input_str, input_time_format)
print(datetime_str.minute)
if datetime_str.minute == 0:
pass
You can check more details about input format here: https://docs.python.org/3/library/datetime.html
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
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 need to convert dates that look like this "2/28/2012" into Feb 28, 2012.
Anyone know how to do this using string slicing, split, and datetime?
Just using datetime.datetime:
from datetime import datetime
date_str = '2/28/2014'
new_date_str = datetime.strptime(date_str, '%m/%d/%Y').strftime('%b %d, %Y')
>>> print new_date_str
Feb 28, 2014
strptime() parses the date string into a datetime.datetime object. strftime() converts that datetime back to a string in the required format.
If you want to do it with string operations:
months = {'1': 'Jan', '2': 'Feb', '3': 'Mar', ...., '12': 'Dec'}
date_str = '2/28/2014'
month, day, year = date_str.split('/')
new_date_str = '{} {}, {}'.format(months[month], day, year)
Yes you can. Try something like this...
from calendar import month_abbr
dateNonFormat = "2/28/2012"
splitDate = dateNonFormat.split("/")
monthFormatted = month_abbr[int(splitDate[0])]
formattedDate = "%s %s, %s" % (monthFormatted, s[1], s[2])
In this example your formatted date would be Feb 28, 2012
You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.string_to_string('2/28/2012', '%m/%d/%Y', '%b %d, %Y')
I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays January [01] [2009].
date=input('Enter a date(mm/dd/yyy)')
replace=date.replace('/',' ')
convert=replace.split()
day=convert[1:2]
year=convert[2:4]
for ch in convert:
if ch[:2]=='01':
print('January ',day,year )
Thank you in advance!
Don't reinvent the wheel and use a combination of strptime() and strftime() from datetime module which is a part of python standard library (docs):
>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy): ')
Enter a date(mm/dd/yyyy): 11/01/2013
>>> date_object = datetime.strptime(date_input, '%m/%d/%Y')
>>> print(date_object.strftime('%B %d, %Y'))
November 01, 2013
You might want to look into python's datetime library which will take care of interpreting dates for you. https://docs.python.org/2/library/datetime.html#module-datetime
from datetime import datetime
d = input('Enter a date(mm/dd/yyy)')
# now convert the string into datetime object given the pattern
d = datetime.strptime(d, "%m/%d/%Y")
# print the datetime in any format you wish.
print d.strftime("%B %d, %Y")
You can check what %m, %d and other identifiers stand for here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
As a suggestion use dateutil, which infers the format by itself:
>>> from dateutil.parser import parse
>>> parse('01/05/2009').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009-JAN-5').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009.01.05').strftime('%B %d, %Y')
'January 05, 2009'
Split it by the slashes
convert = replace.split('/')
and then create a dictionary of the months:
months = {1:"January",etc...}
and then to display it do:
print months[convert[0]] + day + year