I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.
Is this easily doable? Could anyone help?
Thanks :)
The strftime() method takes one or more format codes as an argument and returns a formatted string based on it. We imported datetime class from the datetime module. It's because the object of datetime class can access strftime() method. The datetime object containing current date and time is stored in now variable.
So, 12 PM is 12/24 = . 5, 6:00 AM is 6/24 = . 25, and so on. So, to convert a time by a given number, you need to divide the number of hours by 24 to get required decimal value: E5 / 24 // convert...
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
$time = '2013-01-22 10:45:45'; echo $time = date("H:i:s",strtotime($time));
It will give the time 10:45:45
from datetime.
<?PHP $addhours = 3; $date = DateTime::createFromFormat('YmdHis', '20110805124000'); $shorttime = $date->format("H:i"); $newdate = $date->add(DateInterval::createFromDateString($addhours . "hours")); $newtime = $newdate->format("H:i"); echo $shorttime . "<br />"; echo $newtime . "<br />"; ?>
for your reference:
http://www.php.net/manual/en/datetime.createfromformat.php
http://www.php.net/manual/en/dateinterval.createfromdatestring.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With