This question already has answers here:
Apply timezone offset to datetime in Python
(3 answers)
Closed 4 years ago.
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from dateutil.tz import gettz
from datetime import datetime, timedelta
input_time = '2019-02-01 09:50:08+11:00'
parsed=parse(input_time)
print parsed.tzinfo
I have a time input string:
input_time = '2019-02-01 09:50:08+11:00'
I want to convert it into this format: YYYY-MM-DD HH:MM:SS. Basically, adding the offset to the actual time object. For the above example I am looking for below output:
input_time_converted = '2019-02-01 20:50:08'
Found some useful stuff in dateutil library to parse the date object passed as a string and get the offset details but it gives me this output:
tzoffset(None, 39600)
But I don't know how to get the actual digits from the above and do the rest of the maths.
I have tried to call it with -as explained in the official dateutil parser documentation-
print parsed.tzinfo.tzoffset
But didn't work.
#!/usr/bin/env python2
def process_messed_up_timestamp(ts):
"""Convert messed up timestamps to something else.
Input timestamp is in UTC format with the offset that
should be applied but hasn't been.
"""
from datetime import datetime, timedelta
timestamp, plus, offset = ts[:19], ts[19], ts[20:]
# should validate plus is '+' or '-'
fmt = '%Y-%m-%d %H:%M:%S'
base = datetime.strptime(timestamp, fmt)
hours, minutes = [int(n) for n in offset.split(':')]
delta = timedelta(hours=hours, minutes=minutes)
multiplier = -1 if plus == '-' else 1
return (base + multiplier * delta).strftime(fmt)
input_time = '2019-02-01 09:50:08+11:00'
input_time_converted = '2019-02-01 20:50:08'
assert process_messed_up_timestamp(input_time) == input_time_converted
Related
I'm trying to investigate the Python time striptime method to decompose a time represented as 11:49:57.74. The standard %H, %M, %S are able to decompose the hour , minute , second. However, since the data is a string ( which is taken in python pandas column as datatype object, the Milliseconds after the decimal second is left uninterpreted. Hence, I get an error. Could someone please advise how to parse the example so that the seconds and microseconds are correctly interpreted from the time string ?
I would then use them to find the time delta between two time stamps.
I don't know if I had correctly understood your question.
So, to convert that string time to datetime and calculate the timedelta between two times you need to do as follow:
timedelta = str() #declare an empty string where save the timedelta
my_string = '11:49:57.74' # first example time
another_example_time = '13:49:57.74' #second example time, invented by me for the example
first_time = datetime.strptime(my_string, "%H:%M:%S.%f") # extract the first time
second_time = datetime.strptime(another_example_time , "%H:%M:%S.%f") # extract the second time
#calculate the time delta
if(first_time > second_time):
timedelta = first_time - second_time
else:
timedelta = second_time - first_time
print "The timedelta between %s and %s is: %s" % (first_time, second_time, timedelta)
Here obviusly you don't have any date, so the datetime library as default use 1900-01-01 as you can see in the result of the print:
The timedelta between 1900-01-01 11:49:57.740000 and 1900-01-01 13:49:57.740000 is: 2:00:00
I hope this solution is what you need. Next time provide a little bit more information please, or share an example with the code that you have tried to write.
Django's humanize module is fantastic for turning datetime objects into something that makes more sense to us as humans with it's naturaltime function (docs). What I'm trying to do is the reverse, taking any one of the naturaltime formats and converting it back to a datetime (accepting the obvious loss of precision).
Is there any existing library to do this or am I going to have to write my own datetime.strptime patterns?
I know this is a bit of a "find me a tool/library" question, but I've googled around quite a bit with no results.
For any future searchers, I ended up writing dehumanize to handle this question. It's on github here.
from datetime import datetime, timedelta
import re
def naturaltime(text, now=None):
"""Convert a django naturaltime string to a datetime object."""
if not now:
now = datetime.now()
if text == 'now':
return now
if "ago" in text:
multiplier = -1
elif "from now" in text:
multiplier = 1
else:
raise ValueError("%s is not a valid naturaltime" % text)
text = text.replace('an ', '1 ')
text = text.replace('a ', '1 ')
days = get_first(r'(\d*) day', text)
hours = get_first(r'(\d*) hour', text)
minutes = get_first(r'(\d*) minute', text)
seconds = get_first(r'(\d*) second', text)
delta = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
delta *= multiplier
return now + delta
def get_first(pattern, text):
"""Return either a matched number or 0."""
matches = re.findall(pattern, text)
if matches:
return int(matches[0])
else:
return 0
How would I convert the result from strptime into an integer value or a value that can be used by date.date()?
convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = datetime.datetime(convertTOdate)
A Solution on stackoverflow was to do:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(struct))
I do not want to get the local time as it would not work with my function
I am using Python 2
Thank you
You can use the following approach.
from datetime import datetime
def time_in_seconds(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
convertTOdate = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = time_in_seconds(convertTOdate)
returns 1184752999.0 which is equivalent to 2007-07-18 10:03:19
duedate = datetime.utcfromtimestamp(duedate)
print duedate
Just remember before using the following two:
fromtimestamp give you the date and time in local time and utcfromtimestamp gives you the date and time in UTC.
In my Django project, I have a form (forms.py) which implements pytz to get current timezone like this:
tz = timezone.get_current_timezone()
and I have passed this value to a form field as an initial value like this:
timezone = forms.CharField(label='Time Zone', initial=tznow)
which gives the field a default value of current Timezone, in my case, it happens to be Asia/Calcutta.
Now i want to find the UTC Offset value for the given Timezone, which in this case Asia/Calcutta is +5:30
I tried tzinfo() method as well, but i couldn't find the expected result. Can somebody guide me through this?
The UTC offset is given as a timedelta by the utcoffset method of any implementation of tzinfo such as pytz. For example:
import pytz
import datetime
tz = pytz.timezone('Asia/Calcutta')
dt = datetime.datetime.utcnow()
offset_seconds = tz.utcoffset(dt).total_seconds()
offset_hours = offset_seconds / 3600.0
print "{:+d}:{:02d}".format(int(offset_hours), int((offset_hours % 1) * 60))
# +5:30
A single timezone such as Asia/Calcutta may have different utc offsets at different dates. You can enumerate the utc offsets known so far using pytz's _tzinfos in this case:
>>> offsets = {off for off, dst, abbr in pytz.timezone('Asia/Calcutta')._tzinfos}
>>> for utc_offset in offsets:
... print(utc_offset)
...
5:30:00
6:30:00
5:53:00
To get the current utc offset for a given timezone:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
utc_offset = datetime.now(pytz.timezone('Asia/Calcutta')).utcoffset()
print(utc_offset)
# -> 5:30:00
In case you just want the normalized hour offset:
def curr_calcutta_offset():
tz_calcutta = pytz.timezone('Asia/Calcutta')
offset = tz_calcutta.utcoffset(datetime.utcnow())
offset_seconds = (offset.days * 86400) + offset.seconds
offset_hours = offset_seconds / 3600
return offset_hours
curr_calcutta_offset()
# 5.5
I am importing data from a JSON file and it has the date in the following format 1/7/11 9:15
What would be the best variable type/format to define in order to accept this date as it is? If not what would be the most efficient way to accomplish this task?
Thanks.
"What would be the best variable type/format to define in order to accept this date as it is?"
The DateTimeField.
"If not what would be the most efficient way to accomplish this task?"
You should use the datetime.strptime method from Python's builtin datetime library:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.
Here is a working example (with many debug prints and step-by-step instructions:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style