logo
down
shadow

How do I convert timedelta to time in Python?


How do I convert timedelta to time in Python?

By : mikejm
Date : November 17 2020, 04:28 AM
fixed the issue. Will look into that further If waiting_time is a datetime, then waiting_time - timedelta() is also a datetime. You can just use .time() on that object to get the datetime.time() object from that:
code :
new_dt = waiting_time - timedelta(microseconds=waiting_time.microseconds)
col_7 = new_dt.time()
col_7 = waiting_time.replace(microsecond=0).time()
col_7 = waiting_time.strftime('%H:%M:%S')  # hours:minutes:seconds


Share : facebook icon twitter icon
timedelta convert to time or int and store it in GAE (python) datastore

timedelta convert to time or int and store it in GAE (python) datastore


By : mipi
Date : March 29 2020, 07:55 AM
it fixes the issue To make this as easy as possible to work with, there's two steps: Converting the timedelta to an int or a float, and storing it in the datastore. First things first, converting a timedelta to a microtime:
code :
def timedelta_to_microtime(td):
  return td.microseconds + (td.seconds + td.days * 86400) * 1000000
class TimeDeltaProperty(db.Property):
  def get_value_for_datastore(self, model_instance):
    value = self.__get__(model_instance, model_instance.__class__)
    if value is not None:
      return timedelta_to_microtime(value)

  def make_value_from_datastore(self, value):
    if value is not None:
      return datetime.timedelta(microseconds=value)
class MyModel(db.Model):
  td = TimeDeltaProperty(required=True)

entity = MyModel(td=datetime.datetime.now()-some_datetime)
key = entity.put()

entity = db.get(key)
print entity.td
Python convert military time user input and calculate time worked (datetime.timedelta)

Python convert military time user input and calculate time worked (datetime.timedelta)


By : Kasdi Rabil
Date : March 29 2020, 07:55 AM
I hope this helps . You can use strftime("%I:%M %p") to get standard 12 hour formatting with "AM" or "PM" at the end. See the Python documentation for more details on datetime string formatting.
Also, while it is not natively supported, you can simply use the two datetime.time instances to do your calculation as part of the timedelata constructor.
code :
start = raw_input("Enter your check-in time in military format (0900): ") 
end = raw_input("Enter your check-out time in military format (1700): ") 

# convert user input to datetime instances
start_t = datetime.time(hour=int(start[0:2]), minute=int(start[2:4]))
end_t = datetime.time(hour=int(end[0:2]), minute=int(end[2:4]))
delta_t = datetime.timedelta(
    hours = (end_t.hour - start_t.hour),
    minutes = (end_t.minute - start_t.minute)
    )

# datetime format
fmt = "%I:%M %p"
print 'You started at %s and ended at %s' % (start_t.strftime(fmt), end_t.strftime(fmt))
print 'You worked for %s' % (delta_t)
Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta  string  timedelta

Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta string timedelta


By : Adrian Rumin
Date : March 29 2020, 07:55 AM
this one helps. After searching for such functions, and not being able to find one that converts back and forth, I wrote the following two functions and include them in a script. This is compatible with Python v2.6.6, which doesn't support some newer features such as timedelta.total_seconds():
code :
#!/usr/bin/python

import re
import sys
import datetime

# String from Date/Time Delta:
#  Takes a datetime.timedelta object, and converts the internal values
#  to a dd:HH:mm:ss:ffffff string, prefixed with "-" if the delta is
#  negative
def strfdelta(tdelta):

    # Handle Negative time deltas
    negativeSymbol = ""
    if tdelta < datetime.timedelta(0):
        negativeSymbol = "-"

    # Convert days to seconds, as individual components could
    # possibly both be negative
    tdSeconds = (tdelta.seconds) + (tdelta.days * 86400)

    # Capture +/- state of seconds for later user with milliseonds calculation
    secsNegMultiplier = 1
    if tdSeconds < 0:
        secsNegMultiplier = -1

    # Extract minutes from seconds
    tdMinutes, tdSeconds = divmod(abs(tdSeconds), 60)

    # Extract hours from minutes
    tdHours, tdMinutes = divmod(tdMinutes, 60)
    # Extract days from hours
    tdDays, tdHours = divmod(tdHours, 24)

    # Convert seconds to microseconds, as individual components 
    # could possibly both be negative
    tdMicroseconds = (tdelta.microseconds) + (tdSeconds * 1000000 * secsNegMultiplier)

    # Get seconds and microsecond components
    tdSeconds, tdMicroseconds = divmod( abs(tdMicroseconds), 1000000)

    return "{negSymbol}{days}:{hours:02d}:{minutes:02d}:{seconds:02d}:{microseconds:06d}".format(
        negSymbol=negativeSymbol,
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)


# Date/Time delta from string
# Example: -1:23:32:59:020030 (negative sign optional)
def deltafstr(stringDelta):

    # Regular expression to capture status change events, with groups for date/time, 
    #  instrument ID and state
    regex = re.compile("^(-?)(\d{1,6}):([01]?\d|2[0-3]):([0-5][0-9]):([0-5][0-9]):(\d{6})$",re.UNICODE)
    matchObj = regex.search(stringDelta)

    # If this line doesn't match, return None
    if(matchObj is None):
        return None;

    # Debug - Capture date-time from regular expression 
    # for g in range(0, 7):
    #     print "Grp {grp}: ".format(grp=g) + str(matchObj.group(g)) 

    # Get Seconds multiplier (-ve sign at start)
    secsNegMultiplier = 1
    if matchObj.group(1):
        secsNegMultiplier = -1

    # Get time components
    tdDays = int(matchObj.group(2)) * secsNegMultiplier
    tdHours = int(matchObj.group(3)) * secsNegMultiplier
    tdMinutes = int(matchObj.group(4)) * secsNegMultiplier
    tdSeconds = int(matchObj.group(5)) * secsNegMultiplier
    tdMicroseconds = int(matchObj.group(6)) * secsNegMultiplier

    # Prepare return timedelta
    retTimedelta = datetime.timedelta(
        days=tdDays,
        hours=tdHours,
        minutes=tdMinutes,
        seconds=tdSeconds,
        microseconds=tdMicroseconds)

    return retTimedelta;
# Testing (change the constructor for timedelta to test other cases)
firstDelta = datetime.timedelta(seconds=-1,microseconds=999999, days=-1)
print "--------"
print firstDelta
firstDeltaStr = strfdelta(firstDelta)
print "--------"
print firstDeltaStr;
secondDelta = deltafstr(firstDeltaStr)
print "--------"
print secondDelta
secondDeltaStr = strfdelta(secondDelta)
print "--------"
print secondDelta
print "--------"
Convert datetime.time into datetime.timedelta in Python 3.4

Convert datetime.time into datetime.timedelta in Python 3.4


By : prateek raj
Date : March 29 2020, 07:55 AM
wish help you to fix your issue datetime.time() is not a duration, it is a point in a day. If you want to interpret it as a duration, then convert it to a duration since midnight:
code :
datetime.combine(date.min, timeobj) - datetime.min
>>> from datetime import datetime, date, time
>>> timeobj = time(12, 45)
>>> datetime.combine(date.min, timeobj) - datetime.min
datetime.timedelta(0, 45900)
How to convert timedelta to time of day in pandas?

How to convert timedelta to time of day in pandas?


By : aeron frier
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Pandas does not support a time dtype series
Pandas (and NumPy) do not have a time dtype. Since you wish to avoid Pandas timedelta, you have 3 options: Pandas datetime, Python datetime.time, or Python str. Below they are presented in order of preference. Let's assume you start with the following dataframe:
Related Posts Related Posts :
  • Remove commas in a string, surrounded by a comma and double quotes / Python
  • How to chain Django querysets preserving individual order
  • Comparison with Python
  • How to find backlinks in a website with python
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org