I have a string as Julian date like "16152" meaning 152'nd day of 2016 or "15234" meaning 234'th day of 2015.
How can I convert these Julian dates to format like 20/05/2016 using Python 3 standard library?
I can get the year 2016 like this: date = 20 + julian[0:1], where julian is the string containing the Julian date, but how can I calculate the rest according to 1th of January?
The .strptime() method supports the day of year format:
>>> import datetime
>>>
>>> datetime.datetime.strptime('16234', '%y%j').date()
datetime.date(2016, 8, 21)
And then you can use strftime() to reformat the date
>>> date = datetime.date(2016, 8, 21)
>>> date.strftime('%d/%m/%Y')
'21/08/2016'
Well, first, create a datetime object (from the module datetime)
from datetime import datetime
from datetime import timedelta
julian = ... # Your julian datetime
date = datetime.strptime("1/1/" + jul[:2], "%m/%d/%y")
# Just initializing the start date, which will be January 1st in the year of the Julian date (2 first chars)
Now add the days from the start date:
daysToAdd = int(julian[2:]) # Taking the days and converting to int
date += timedelta(days = daysToAdd - 1)
Now, you can just print it as is:
print(str(date))
Or you can use strftime() function.
print(date.strftime("%d/%m/%y"))
Read more about strftime format string here
Easy way
Convert from regular date to Julian date
print datetime.datetime.now().strftime("%y%j")
Convert from Julian date to regular date
print datetime.datetime.strptime('19155', '%y%j').strftime("%d-%m-%Y")
I used this for changing a Juian date to xml xsd:datetime
def julianDate2ISO8601(d, offset='+00:00'):
"""
return ISO8601 formated datetime from julian date
optional offset [+|-]hh:mm
"""
d = str(d) # make sure it is a string
# replace leading number with correct century
centuryArray = ['19','20','21']
d = centuryArray[int(d[:1])] + d[1:]
# format string to iso 8601 datetime
return datetime.datetime.strptime(d, '%Y%j').date().strftime(
'%Y-%m-%dT00:00:00') + offset
Related
Does anyone know how I can extract the end 6 characters in a absoloute URL e.g
/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104
This is not a typical URL sometimetimes it ends -221104
Also, is there a way to turn 221104 into the date 04 11 2022 easily?
Thanks in advance
Mark
You should use the datetime module for parsing strings into datetimes, like so.
from datetime import datetime
url = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
datetime_string = url.split('--')[1]
date = datetime.strptime(datetime_string, '%y%m%d')
print(f"{date.day} {date.month} {date.year}")
the %y%m%d text tells the strptime method that the string of '221104' is formatted in the way that the first two letters are the year, the next two are the month, and the final two are the day.
Here is a link to the documentation on using this method:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
If the url always has this structure (that is it has the date at the end after a -- and only has -- once), you can get the date with:
str_date = str(url).split("--")[1]
Relaxing the assumption to have only one --, we can have the code working by just taking the last element of the splitted list (again assuming the date is always at the end):
str_date = str(url).split("--")[-1]
(Thanks to #The Myth for pointing that out)
To convert the obtained date into a datetime.date object and get it in the format you want:
from datetime import datetime
datetime_date = datetime.strptime(str_date, "%y%m%d")
formatted_date = datetime_date.strftime("%d %m %Y")
print(formatted_date) # 04 11 2022
Docs:
strftime
strptime
behaviour of the above two functions and format codes
Taking into consideration the date is constant in the format yy-mm-dd. You can split the URL by:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
To convert yy-mm-dd into dd mm yy we will use the DateTime module:
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d-%m-%Y') # Format
print(format_time)
The whole code looks like this:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d %m %Y') # Format
print(format_time)
Learn more about datetime
You can use python built-in split function.
date = url.split("--")[1]
It gives us 221104
then you can modify the string by rearranging it
date_string = f"{date[4:6]} {date[2:4]} {date[0:2]}"
this gives us 04 11 22
Assuming that -- will only be there as it is in the url you posted, you can do something as follows:
You can split the URL at -- & extract the element
a = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
desired_value = a.split('--')[1]
& to convert:
from datetime import datetime
converted_date = datetime.strptime(desired_value , "%y%m%d")
formatted_date = datetime.strftime(converted_date, "%d %m %Y")
I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02
I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass
I have a date time object that looks like:
2015-31-12 00:34:00
where the second element (31) represents the day and the third element (12) represents the month. How do I swap day and month so that the date looks like:
2015-12-31 00:34:00
You'd parse the string into a datetime object then format it again back to a string:
from datetime import datetime
result = datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
Demo:
>>> from datetime import datetime
>>> inputstring = '2015-31-12 00:34:00'
>>> datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
'2015-12-31 00:34:00'
So the datetime.strptime() parses the string given a pattern, where you specify that the order is year-day-month, and datetime.strftime() formats it back to a string, with the day and month positions swapped.
Use .strftime('%Y-%m-%d %H:%M:%S').
For example:
from datetime import datetime
formatted_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
Please what's wrong with my code:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)
Display "2013-01-01 00:00:00", Thanks.
A week number is not enough to generate a date; you need a day of the week as well. Add a default:
import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)
The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:
2013-07-01 00:00:00
%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.
See the strftime() and strptime() behaviour section in the documentation, footnote 4:
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the year are specified.
Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.
In Python 3.8 there is the handy datetime.date.fromisocalendar:
>>> from datetime import date
>>> date.fromisocalendar(2020, 1, 1) # (year, week, day of week)
datetime.date(2019, 12, 30, 0, 0)
In older Python versions (3.7-) the calculation can use the information from datetime.date.isocalendar to figure out the week ISO8601 compliant weeks:
from datetime import date, timedelta
def monday_of_calenderweek(year, week):
first = date(year, 1, 1)
base = 1 if first.isocalendar()[1] == 1 else 8
return first + timedelta(days=base - first.isocalendar()[2] + 7 * (week - 1))
Both works also with datetime.datetime.
To complete the other answers - if you are using ISO week numbers, this string is appropriate (to get the Monday of a given ISO week number):
import datetime
d = '2013-W26'
r = datetime.datetime.strptime(d + '-1', '%G-W%V-%u')
print(r)
%G, %V, %u are ISO equivalents of %Y, %W, %w, so this outputs:
2013-06-24 00:00:00
Availabe in Python 3.6+; from docs.
import datetime
res = datetime.datetime.strptime("2018 W30 w1", "%Y %W w%w")
print res
Adding of 1 as week day will yield exact current week start. Adding of timedelta(days=6) will gives you the week end.
datetime.datetime(2018, 7, 23)
If anyone is looking for a simple function that returns all working days (Mo-Fr) dates from a week number consider this (based on accepted answer)
import datetime
def weeknum_to_dates(weeknum):
return [datetime.datetime.strptime("2021-W"+ str(weeknum) + str(x), "%Y-W%W-%w").strftime('%d.%m.%Y') for x in range(-5,0)]
weeknum_to_dates(37)
Output:
['17.09.2021', '16.09.2021', '15.09.2021', '14.09.2021', '13.09.2021']
In case you have the yearly number of week, just add the number of weeks to the first day of the year.
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)
Another solution which worked for me that accepts series data as opposed to strptime only accepting single string values:
#fw_to_date
import datetime
import pandas as pd
# fw is input in format 'YYYY-WW'
# Add weekday number to string 1 = Monday
fw = fw + '-1'
# dt is output column
# Use %G-%V-%w if input is in ISO format
dt = pd.to_datetime(fw, format='%Y-%W-%w', errors='coerce')
Here's a handy function including the issue with zero-week.