get year from string '07-JUL-50' [duplicate] - python

This question already has answers here:
2 digit years using strptime() is not able to parse birthdays very well
(3 answers)
Closed 9 years ago.
I have a birth date field like:
date = '07-JUL-50'
and when I wanna get the year I got this:
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
>>> my_date.year
2050
Is there an elegant way of get '1950'??
Thx

Documentation says that:
When 2-digit years are accepted, they are converted according to the
POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and
values 0–68 are mapped to 2000–2068.
That's why you are seeing 2050.
If you want 1950 instead, it depends on what are allowed dates in your particular scenario. E.g. if date values can be only dates in the past, you can do something like this:
import datetime
def get_year(date):
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
now = datetime.datetime.now()
if my_date > now:
my_date = my_date.replace(year=my_date.year - 100)
return my_date.year
print get_year('07-JUL-50') # prints 1950
print get_year('07-JUL-13') # prints 2013
print get_year('07-JUL-14') # prints 1914
Hope that helps.

Related

Convert a number sequence into a date using python? (example: 221201) [duplicate]

This question already has answers here:
How can I convert a string into a date object and get year, month and day separately?
(4 answers)
Closed 2 months ago.
I have a bunch of number sequences like "221201" meaning the year 2022, month 12 and day 01 (so 2022-12-01). How can I convert number sequences in this format into the actual date using python?
I've tried using the dateutil library but couldn't figure out how to get it to recognize this format.
from datetime import datetime
date_str = '221201'
date_obj = datetime.strptime(date_str, '%y%m%d')
print(type(date_obj))
print(date_obj) # printed in default format
You can learn more about strptime in this link

Convert date string format to a datetime Python Object [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
i've one doubt.
I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:
{"date":"2020-08-24T21:15:00+00:00"}
I want to get a python datetime object.
How can I do that?
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Use dateutil.parser which smartly parse date string:
import json
import dateutil.parser
result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])
# 2020-08-24 21:15:00+00:00
print(dt)
# <class 'datetime.datetime'>
print(type(dt))
I think you can do it respecting the format while parsing the string:
You have to try to follow the structure of the string and assign each value to the correct time value. For example:
str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
Note that your case is pretty different.
It could be similar to '%Y-%m-%dT%H:%M:%S.f'

Python dateutil returns YYYY-MM-DD, but I need it reversed , help please? [duplicate]

This question already has answers here:
How to print a date in a regular format?
(25 answers)
Closed 4 years ago.
I've got a piece of script in python that parses a line containing date and time:
d = dateutil.parser.parse("%s %s" % (m.group('date'),
m.group('time')), dayfirst=True)
it returns the date in YYYY-MM-DD. How can I get it to say Weekday DD Month YYYY? Or if that is not possible DD-MM-YYYY?
Additionally, it also gives the time in HH:MM:SS, but I only need HH:MM, is there a way to lose the seconds?
Thank you!
I'm a complete novice to python so hope that anyone can help me, thank you very much!
Use datetime module's strftime to change the format according to the docs.
d = '2019-01-09'
d = datetime.datetime.strptime(d, '%Y-%m-%d')
print(d)
d = d.strftime('%A %d %B %Y %H:%M') # %I:%M if you want 12 hour format
print(d) # Wednesday 09 January 2019 00:00
from datetime import date, timedelta
day = date.today() # this gives you output in default YYYY-MM-DD format
now = datetime.now() # this give your output in default YYYY-MM-DD hh:mm:ss.millisec format
timestamp = now.strftime('%d-%m-%Y-%H:%M') # this gives you the output in the format you are looking for. See the screenshot
Have a look at this link for further details: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

How to convert a string to datetime object [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 5 years ago.
With the time value being:
value = '2017-08-31T02:24:29.000Z'
I try to convert it to a datetime object with:
import datetime
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d %I:%M%p')
But the command crashes with the exception:
ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d %I:%M%p'
You should be using a builtin Python's datautil module instead of date time:
import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)
First of all, you are missing the formatter for the microsecond.
Second of all, there is no second colon for dividing the minute and second.
Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.
Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.
This is your code:
datetime_object = datetime.datetime.strptime(value, '%Y-%m-%dT%I:%M:%S.%fZ')
You should get 2017-08-31 02:24:29 as the value of datetime_object.

how to get week number on python? [duplicate]

This question already has answers here:
Python: Number of the Week in a Month
(9 answers)
Closed 7 years ago.
I want to get week number like picture below
If I insert 20150502, It should print "week 1".
If I insert 20150504, It should print "week 2".
If I insert 20150522, It should print "week 4".
How to get week number?
Here's a quick attempt, as with all date/time code there are probably a lot of edge cases that can cause strange results.
# dateutil's parser is very good for converting from string to date
from dateutil.parser import parse
date_strs = ['20150502', '20150504', '20150522']
for date_str in date_strs:
d = parse(date_str)
month_start = datetime.datetime(d.year, d.month, 1)
week = d.isocalendar()[1] - month_start.isocalendar()[1] + 1
print(date_str + ':', week)
Output:
20150502: 1
20150504: 2
20150522: 4

Categories