Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
SamAnw

Python time

Recommended Posts

Posted · Original PosterOP

Hello

I have to write a python program that changes an input file like the following:

1 hour 20 minutes

30 minutes and 2 hours

into an output file like the following:

01:20:00

02:30:00

I have no idea what to do :/ Thankyou!

Link to post
Share on other sites
1 hour ago, SamAnw said:

Hello

I have to write a python program that changes an input file like the following:

1 hour 20 minutes

30 minutes and 2 hours

into an output file like the following:

01:20:00

02:30:00

I have no idea what to do :/ Thankyou!

If you are allowed to use pre-existing functions that do exactly what you want, take a look at strptime()


Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

If you can't do what @WereCatf suggested, look at what the .split() method of strings does. Also take a look at the re module for regular expressions.


...is there a question here? ?

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP

Hello everyone,

I need to create a program that converts an input like this one:

1m and 45s
10m,10s
32s, and 12h
76h
1s

Into an output like this one:

00:01:45
00:10:10
12:00:32
76:00:00
00:00:01

 

Does anyone have an idea of how to do this?

 

Thanks in advance

 

 

Link to post
Share on other sites

Hi @SamAnw, you have started a few threads, all related to the same thing. this questions has already been asked and people offered their help. If you need more help, continue on those threads, rather than starting new ones every 30 minutes.

Link to post
Share on other sites
9 minutes ago, SamAnw said:

Hello everyone,

I need to create a program that converts an input like this one:

1m and 45s
10m,10s
32s, and 12h
76h
1s

Into an output like this one:

00:01:45
00:10:10
12:00:32
76:00:00
00:00:01

 

Does anyone have an idea of how to do this?

 

Thanks in advance

split the strings at the s an m marks (and h for hour) and place it into a a new string with colons inbetween.

do you not have required reading material for this sort of homework that can be consulted? Because otherwise, Googling stuff effectively is also a trait a programmer should build up.


"those times will never come back :("

"I wish I could find a way to end the pain, other than the way I keep thinking of"

Link to post
Share on other sites

* threads merged *


If you need help with your forum account, please use the Forum Support form !

 

VPN server guide

Guide to run any software as Admin

NiceHash Mining Guide

Ethereum Mining Guide

Spoiler

My Gaming Rig - Motherboard: MSI Z370-A PRO CPU: i7-8700 RAM: 32GB DDR4 2400(4x8GB) GPU: Gigabyte GTX 1060 3GB OS SSD: 240GB Avexir E100 Storage: 2x 1TB Seagate PSU: Seasonic G650 OS: Windows 10 Pro 64bits Monitor: Acer 21in G205H + Lenovo 21in

 

Link to post
Share on other sites

tokenize

normalize

simplify

 

replace comma , dot, : , ; and other characters that could exist with a separator (ex 10h,5m ... you'll want to become "10 h 5 m"

parse the string character by character and add a space or some separator between 0..9 and other characters, to convert 10h to "10 h"

convert everything to lowercase or uppercase, because you don't care about case.

split the text into separate chunks based on that separator (usually space character as most common separator)

 

here's how it would work in php

 

<?php 

$text = "10hours and 5 minutes";

$text = strtolower($text); // make everything lowercase
$text = str_replace( array(',',':',';','-','=','.',chr(0x09)) , ' ',$text); // replace with space (0x09 = tab)

$newText = '';
$prev = false; // previous character was not digit
$offset = 0;
while ($offset<strlen($text)) {
    $c = substr($text,$offset,1);
    if ($c>='0' && $c<='9') {
        if ($prev==false) $newText .= ' ';
        $prev = true; 
    } else {
        if ($prev==true) $newText .= ' ';
        $prev = false;
    } 
    $newText .= $c;
    $offset++;
}
// newText is the proper variable now

$words = explode(' ',$newText);
$filteredWords = array();

foreach ($words as $word) {
    $validWord = false;
    if (strlen($word)>0) {
        if (ctype_digit($word)==true) $validWord=true;
        $testWords = array('day','hour','minute','second');
        foreach ($testWords as $testWord) {
            // first letter of each test word (d, h , m)
            if (strlen($word)==1 && substr($word,0,1)==$testWord) $validWord = true;
            // singular (day, hour, minute, second)
            if (strlen($word)==strlen($testWord) && $word==$testWord) $validWord = true;
            // plural - add S to end
            if ((strlen($word)==(strlen($testWord)+1)) && $word==$testWord.'s') $validWord = true; 
        } 
        // only care about first char if it's not a number
        if (ctype_digit($word)==false && $validWord==true) $word = substr($word,0,1); 
        if ($validWord==true) array_push($filteredWords,$word);
    }
}
// filteredWords array contains all the good stuff  
echo implode(' ',$filteredWords); // just for debugging purposes
// now convert everything to seconds
$total = 0;
if (count($filteredWords)>1) {
    for ($i=1;$i<count($filteredWords);$i++) {
        $a = $filteredWords[$i-1];
        $b = $filteredWords[$i];
        if (ctype_digit($a)==true && ctype_digit($b)==false) {
            $a = intval($a);
            if ($b=='s') $total += $a;
            if ($b=='m') $total += $a*60;
            if ($b=='h') $total += $a*3600;
            if ($b=='d') $total += $a*24*3600;
        }
    }
}
// now total holds the number of seconds 
echo $total;
$units = array(0,0,0,0);
if ($total>0) {
    while ($total >= 86400) { $units[0]++;$total = $total - 86400;}
    while ($total >= 3600) { $units[1]++;$total = $total - 3600;}
    while ($total >= 60) { $units[2]++;$total = $total - 60;}
    $units[3] = $total;
}
// finalText dd:hh:mm:ss

$finalText = '';
for($i=0;$i<4;$i++) $finalText .= ':'.str_pad($units[$i],2,'0',STR_PAD_LEFT);
$finalText = trim($finalText,':');

// as an excercise, figure out how to trim 00: from the front if unneeded

echo $finalText;

die();

ex 10hours and 5 minutes => 00:10:05:00
?>

 

Link to post
Share on other sites
On 2/14/2020 at 9:36 AM, SamAnw said:

1m and 45s
10m,10s
32s, and 12h
76h
1s

What were you learning in the class that assigned this at the time that it was assigned?

10 times out of 10, the teacher expects nothing but a solution that uses what they've been teaching you.

If this is not homework, just a hobby, the most robust thing to do is formally define the language, and then build a lexer/parser to do the transformation for you.


I will never succumb to the New Cult and I reject the leadership of @Aelar_Nailo and his wicked parrot armies led by @FakeCIA and @DildorTheDecent. I will keep my eyes pure and remain dedicated to the path of the One True; IlLinusNati

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×