Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alter the time in python?

I wanted to change the minutes/hours of pythonic time. I have a string of time start_time = "2013-09-30 14:12:08.024923". I want it to convert it to its ceil quater,half or full time, ie if I set interval as 15 I should get 2013-09-30 14:15:00.0000. If interval is 30, I should get 2013-09-30 14:15:00.0000

How can I change it?

Here is what I have tried.

start_time = "2013-09-30 14:12:08.024923"
start_time  = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S.%f")
interval = 15
ceil_to = (start_time.minute/interval) *interval + interval

start_time.minute = interval # throws error saying attribute 'minute' of 'datetime.datetime' objects is not writable

How do I achieve this?

like image 459
PythonEnthusiast Avatar asked Oct 01 '13 04:10

PythonEnthusiast


People also ask

How do you edit datetime?

You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.

How does Python sync time?

Copy the the contents of the code below to a file (I named mine "synctime.py"). Then, after the network is running, execute the script (e.g. "python synctime.py"). You will need to do this using elevated (root) privileges for this to work properly. import time import os try: import ntplib client = ntplib.


1 Answers

You can do this with replace:

start_time = start_time.replace(minute=ceil_to, second=0, microsecond=0)
like image 149
David Robinson Avatar answered Sep 18 '22 20:09

David Robinson